exception handling in complex Python programs

Bruno Desthuilliers bruno.42.desthuilliers at websiteburo.invalid
Wed Aug 20 12:40:49 EDT 2008


eliben a écrit :
> 
> This is *exactly* my concern with Python exceptions. You just never
> know what can be thrown at you.

This rarely happen to be a problem in real life. At least not in mine.

Exception that can be expected (ie : IOError when dealing with files) 
are usually obvious and more or less documented - or easy to figure out 
(like TypeError and ValueError when trying to build an int from an 
arbitrary object, KeyError when working with dicts, AttributeError when 
inspecting an object, etc) from concrete use.

IOW, it's usually easy to know which exceptions you're able to deal with 
at the lower level.

Any other exception is either a programming error - which needs to be 
fixed, not hidden - or nothing you can deal with at the lower level - in 
which case just let it propagate until some other layer above deal with 
it (eventually just logging the error, displaying a user-friendly 
message, and crashing if nothing else is possible).



>>   def do_something(filename):
>>     if not os.access(filename,os.R_OK):
>>       return err(...)
>>     f = open(filename)
>>     ...
>>
> 
> But does os.access cover absolutely all the errors that can happen
> during open() ? What guarantees it, and how can I know without you
> teaching me, just from the docs ?

The above code is a perfect antipattern. It's useless (if you can't 
access the file, you'll get an IOError when trying to open it anyway), 
it's wrong (things may change between the call to os.access and the call 
to open), and it defeats the whole point of exception handling (by 
returning some kind of error object instead of using exception handling).




More information about the Python-list mailing list