Best practice for handling exceptions raised at lower levels?

Greg Ewing greg.ewing at canterbury.ac.nz
Tue Feb 2 19:16:35 EST 2021


On 3/02/21 9:24 am, Dan Stromberg wrote:

> But how do you know what exceptions could be raised?

Mostly I find that it's not really necessary to know precisely
which exceptions could be raised.

The way I usually deal with exceptions is:

1. If it descends from OSError, I assume it results from some
external condition, so I catch it at a level where I know what
the user was trying to accomplish and can report it in a
meaningful way. E.g.

     def open_connection(address):
         try:
             return some_library.open_thing(address)
         except OSError as e:
             tell_user("Couldn't connect to %s: %s" % (address, e))

2. If it's anything else, I assume it's a bug and let it
propagate.

-- 
Greg


More information about the Python-list mailing list