Sorting out which exceptions to handle

Francis Avila francisgavila at yahoo.com
Mon Nov 3 23:32:54 EST 2003


"Derek Fountain" <nomail at hursley.ibm.com> wrote in message
news:3fa70fe4$0$1740$5a62ac22 at freenews.iinet.net.au...
> The O'Reilly Python in a Nutshell book says "Generally your code uses a
> statement of the form:
>
> try:
>   ...
> except module.Error, err:
>   ...
> "
>
> with the word "module" in italics. I tried the line:
>
> except MySQLdb.Error, err:
>
> and various variations, but always got errors.

The O'Reilly book is simply pointing out a convention.  Usually modules only
need one exception type, and it's called 'Error' (or 'error' for builtin
modules).  It's not some magic syntax or semantics that catches every kind
of exception that a module could raise.

> How do I trap all the database associated errors this module can generate?

Trapping an exception traps all exceptions which are subclasses of that
exception.

E.g.:

>>> class BaseError:
...     pass
...
>>> class SpecialError(BaseError):
...     pass
...
>>> try:
...     raise SpecialError #Implicit class instantiation
... except BaseError, err:
...     print 'Caught instance of BaseError or subclass thereof.'
...     print 'Specifically,', repr(err)
...

Caught instance of BaseError or subclass thereof.
Specifically, <__main__.SpecialError instance at 0x00AB9340>
>>>

Hope this helps.
--
Francis Avila





More information about the Python-list mailing list