Where to handle try-except - close to the statement, or in outer loop?

Terry Reedy tjreedy at udel.edu
Tue Nov 12 03:51:31 CET 2013


On 11/11/2013 8:34 PM, Victor Hooi wrote:

> I have a general question regarding try-except handling in Python.

In Python, try-except can unapologetically be used as as alternate 
conditional-execution control-flow construct.

if <condition>:
   <do something>
else:
   <do something else>

can often be re-written

try:
   <do something>
except <exception indicating that condition was false>:
   <so something else>

Some reasons for using the try_except form:
1. <condition> is volatile and may change between the 'if <condition> 
check and the <do something> performance.
2. <condition> is expensive to check>.
3. <condition> is nearly always True (say >= 90% of the time).

Notice that 'except' is at least as close to 'try' as 'else' is to 'if'.

General rule: handle exceptions as soon as you can do something useful.

You can find lots of examples in the stdlib where <do something> is a 
single simple statement.***  I recommend that beginners try reading some 
of the stdlib code. It is not necessarily all great, but the average 
quality should be pretty decent. Of course, some modules are more recent 
than others.

> Previously, I was putting the try-handle blocks quite close to where
> the errors occured:
>
> A somewhat contrived example:
>
> if __name__ == "__main__": my_pet = Dog('spot', 5, 'brown')
> my_pet.feed() my_pet.shower()
>
> and then, in each of the methods (feed(), shower()), I'd open up
> files, open database connections etc.

Do use with blocks.
>
> And I'd wrap each statement there in it's own individual try-except
> block. (I'm guessing I should wrap the whole lot in a single
> try-except, and handle each exception there?)
>
> However, the author here:
>
> http://stackoverflow.com/a/3644618/139137
>
> suggests that it's a bad habit to catch an exception as early as
> possible, and you should handle it at an outer level.

This was a side comment in a specific context of IOErrors that he thinks 
are best handled later. Perhaps Bernd has seen some useless inner code 
try-excepts that I have not.

> From reading other posts, this seems to be the consensus as well.

As stated above, not among the people who develop Python.

> However, how does this work if you have multiple methods which can
> throw the same types of exceptions?

You have noticed the reason for the *** statement above ;-).

> For example, if both feed() and shower() above need to write to
> files, when you get your IOError, how do you distinguish where it
> came from? (e.g. If you wanted to print a friendly error message,
> saying "Error writing to file while feeding.", or if you otherwise
> wanted to handle it different).
>
> Would I wrap all of the calls in a try-except block?
>
> try: my_pet.feed() my_pet.shower() except IOError as e: # Do
> something to handle exception?
>
> Can anybody recommend any good examples that show current best
> practices for exception handling, for programs with moderate
> complexity? (i.e. anything more than the examples in the tutorial,
> basically).

See comment above about stdlib modules. Pick some that interest you.

-- 
Terry Jan Reedy




More information about the Python-list mailing list