Identifying exceptions that can be raised

Peter Otten __peter__ at web.de
Fri Nov 19 13:35:11 CET 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?
> 
> /Dan

None that I know of. You just have to feed the function the typical data and
any corner cases that you can think of and handle all failures that appear
in the process. The unittest module can help you automate this.
Hoping to ever get a comprehensive set of exceptions a function can raise is
a vain effort in Python. A little example may illustrate this:

>>> def add(a, b):
...     return a + b
...
>>> add(1, 2)
3
>>> add(1, "2")
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
  File "<stdin>", line 2, in add
TypeError: unsupported operand type(s) for +: 'int' and 'str'

The above calls should cover the typical usage of our trivial function. Does
it make sense then, to document/report that add() may raise a TypeError? I
think that would be misleading:

>>> class Int(int):
...     def __add__(self, other):
...             return self/other
...
>>> add(Int(1), 0)
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
  File "<stdin>", line 2, in add
  File "<stdin>", line 3, in __add__
ZeroDivisionError: integer division or modulo by zero

This may seem contrived, but for any non-trivial function the number of
exceptions is open-ended, and trying to achieve reliability by handling a
fixed set of exceptions is essentially asking for type declarations for a
small portion of a function's signature - and a portion where its
usefulness is debated even for statically typed languages (I think Java has
it, but C sharp doesn't).
Put your time to a better use and write a good test suite.

Peter




More information about the Python-list mailing list