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

Victor Hooi victorhooi at gmail.com
Mon Nov 11 20:34:21 EST 2013


Hi,

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

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.

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.

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

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

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).

Cheers,
Victor



More information about the Python-list mailing list