Pythonic way for handling file errors

Paul Hankin paul.hankin at gmail.com
Wed Oct 10 21:28:49 CEST 2007


On Oct 10, 7:41 pm, wink <w... at saville.com> wrote:
> I would like to know what would be considered the most
> Pythonic way of handling errors when dealing with files,
> solutions that seem reasonable using 2.5:

The best way to handle errors is to catch the exceptions that are
raised by the code that handles the error. Your examples push the
problem elsewhere: you're setting an error code which has to be tested
for. But perhaps your application needs to do this for some reason
(judging from your error codes, this is some sort of web script).

> ...
> try:
>    with open('afile', 'r') as f:
>        content = f.read()
>    error = 200
> except Exception:
>    error = 404

Of all your examples, this is the best. But the catch-all exception
handler is bad: it's better to catch just file io exceptions. Also, I
think it's better to put the OK case (error 200) in an else clause to
make it clearer that it's only set when no error occurs. It's also
better to use constants in place of magic numbers.

import httplib

try:
    with open('afile', 'r') as f:
        content = f.read()
except IOError:
    error = httplib.NOT_FOUND
else:
    error = httplib.OK

--
Paul Hankin




More information about the Python-list mailing list