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

Chris Angelico rosuav at gmail.com
Tue Nov 12 02:56:43 CET 2013


On Tue, Nov 12, 2013 at 12:34 PM, Victor Hooi <victorhooi at gmail.com> wrote:
> 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?
>

It really depends more on how you go about recovering from errors. If
feeding the dog and showering the dog are completely independent, you
should catch errors for them separately (probably inside feed() and
shower()), but if a problem with feeding the dog stops you from
showering him, then do what you have here. Catch exceptions where it
makes sense to recover from the issue. Sometimes that means putting a
blanket catch-all at some point ("if anything goes wrong here, log the
error, return an HTTP 500, and go deal with the next query"), and
sometimes it means not catching errors at all (any that bubble all the
way up will get reported on STDERR, which is often the most useful
handling anyway).

ChrisA



More information about the Python-list mailing list