error handling when opening files

Marko Rauhamaa marko at pacujo.net
Tue Jul 8 04:30:50 EDT 2014


Alex Burke <alexjeffburke at gmail.com>:

> While reading up on a previous thread 'open() and EOFError' I saw the
> following (with minor changes to help make my question clearer) block
> suggested as a canonical way to open files and do something:
>
> try:
>     f = open(path)
> except IOError:
>     handle_error()
> else:
>     with f:
>         do_stuff()
>
> This somewhat surprised me because I'd always written such a block
> something more as follows:
>
> try:
>     with open(path) as f:
>         do_stuff()
> except IOError:
>     handle_error('file never opened')
> except ApplicationError:
>     handle_error('doing something with the content went wrong')
>
> Aside from the pythonic but less widely known else clause of the
> try/except in the first form, what else is different? What nuances am
> I missing?

Your version catches IOError for do_stuff() as well as open(). You
usually want to guard each statement with try-except so you can log and
pinpoint the error better.


Marko



More information about the Python-list mailing list