Identifying exceptions that can be raised

Peter Hansen peter at engcorp.com
Fri Nov 19 22:06:32 EST 2004


dkcpub wrote:
> Brian van den Broek wrote:
> 
>> If you mean you want a list of exceptions that a given function could 
>> raise, well, never mind :-)
> 
> Yeah, that is what I mean.  I write foo(), which calls a half-dozen 
> library functions.  What exceptions is a caller of foo() going to have 
> to handle?  It there an automated way of discovering that?

Nope.  That's that nasty ol' Java thinkin'. ;-)

Basically, given the dynamicism that is Python's hallmark,
you can't guarantee that any given function won't raise
an arbitrary exception.  I could write a function that
could raise random exceptions, including ones it wasn't
even previously aware of (by crawling the tree of classes
starting at sys.modules and discovering new ones, perhaps).

The usual approach is to have a caller catch exceptions
*which it is capable of dealing with appropriately*, and
ignore others.  In some cases it's necessary to have a
"generic" exception handler, such as at the top level of
a thread, to catch and log all exceptions, but that's
relatively rare.

In contrast to Java code, you aren't forced to catch
exceptions in a manner similar to the old-style approach
to handling error values returned by functions (that is,
by ignoring them).  Instead you write useful code that
actually explicitly catches only things it understands
and can deal with.  A breath of fresh air, really...

All that said, you do sometimes find yourself pondering
what exceptions a given function might raise and which
you *do* want to handle properly.  It's not always clear,
and unfortunately short of examining the source or hoping
that the author wrote decent documentation, you're out
of luck.

-Peter



More information about the Python-list mailing list