correct way to catch exception with Python 'with' statement

Marko Rauhamaa marko at pacujo.net
Tue Nov 29 04:38:32 EST 2016


Peter Otten <__peter__ at web.de>:

> Marko Rauhamaa wrote:
>
>> However, I think the real answer is that you shouldn't mix the "with"
>> construct with exception handling. Instead you should write:
>> 
>>    try:
>>        f = open("xyz")
>>    except FileNotFoundError:
>>        ...[B]...
>>    try:
>>        ...[A]...
>>    finally:
>>        f.close()
>
> What's the problem with spelling the above
>
> try: 
>     f = open(...)
> except FileNotFoundError:
>     ...
> with f:
>     ...

Nothing.


Marko



More information about the Python-list mailing list