error handling when opening files

Alex Burke alexjeffburke at gmail.com
Mon Jul 7 19:49:58 EDT 2014


Hi there,

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?

The reason I preferred the second was in addition to catching the
IOError when attempting the open() if the file does not exist I
thought I was accounting for the possibility en error occurs while
reading data out of the file. That and to handle if do_stuff() was
actually calling readline() or such on the file which I thought was
possible source of issues.

I am wondering if this is also related to some misunderstanding around
the file context manager - on exit of the with() block a close is
arranged, but if that close() is called in an error situation I was
under the impression that the error would be raised again outside it.
Otherwise the only way I can see of getting errors is have a variable
set to None and if the with block succeeds set it to some other value
thus being able to do an if not None check afterward.

That's probably enough conflated questioning for now.. who'd have
thought opening a file could be such a poser! Yep, it's always the
error handling :)

Thanks in advance, Alex J Burke.



More information about the Python-list mailing list