exception handling in complex Python programs

Bruno Desthuilliers bruno.42.desthuilliers at websiteburo.invalid
Thu Aug 21 06:40:15 EDT 2008


eliben a écrit :
> On Aug 19, 7:19 pm, eliben <eli... at gmail.com> wrote:
>> Python provides a quite good and feature-complete exception handling
> <snip>
> 
> Thanks for the interesting discussion. Armed by the new information
> and few online sources, I blogged a summary for myself on the topic of
> robust exception handling in Python:
> 
> http://eli.thegreenplace.net/2008/08/21/robust-exception-handling/
> 
A couple comments (mostly python-specific, so I post them here):

"""
When used for flow-control, exceptions are like goto. There might be a 
few esoteric cases in which they’re appropriate, but 99.99% of the time 
they are not.
"""

Python itself uses exceptions for flow control in iterators.


"""
For some exceptions, like programming errors (e.g. IndexError, 
TypeError, NameError etc.) exceptions are best left to the programmer / 
user, because “handling” them will just hide real bugs.
"""

Depends on the context. There are cases where you expect these kind of 
errors - like when dealing with program inputs, inspecting objects etc. 
As a Q&D example:

while True:
     raw_num = raw_input("enter a number")
     try:
         num = float(raw_num)
     except TypeError, ValueError:
         print "sorry, '%s' is not a valid number" % raw_num
     else:
         # ok
         break



"""
This is also the reason why you should be extremely careful with except: 
clauses that catch everything. These will not only catch the exceptions 
you intended, but all of them.
"""

And remember that SysExit and KeyboardInterrupt *are* exceptions too...

"""
Document the exceptions thrown by your code
"""

If you mean "the exceptions *explicitely raised* by your code", then I 
agree. But with any generic enough code, documenting any possible 
exception that could be raised by lower layers, objects passed in as 
arguments etc is just plain impossible. Like, if you have a function 
that takes a file-like object as arg, you just cannot know in advance 
what exceptions this object might raise.

My 2 cents.



More information about the Python-list mailing list