correct way to catch exception with Python 'with' statement

Marko Rauhamaa marko at pacujo.net
Tue Nov 29 03:27:51 EST 2016


Steven D'Aprano <steve+comp.lang.python at pearwood.info>:
> There is no need to catch the exception if you're not going to do
> anything with it.

Correct. However, the question of the subject line is still a good one.
See:

    try:
        with open("xyz") as f:
            ...[A]...
    except FileNotFoundError:
        ...[B]...

The basic principle about exceptions is that if you are prepared to
catch one, catch it in the immediate vicinity of the operation that
might raise it. The code above might mistakenly catch an exception from
inside the "with" block.

You could then protect yourself like this:

   try:
       with open("xyz") as f:
           try:
               ...[A]...
           except FileNotFoundError as e:
               raise SmuggleItOutException(e)
   except FileNotFoundError:
       ...[B]...
   except SmuggleItOutException as e:
       raise e.exception_proper


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()


Marko



More information about the Python-list mailing list