Custom exceptions -- inherit from exceptions.Exception?

Alex Martelli aleax at aleax.it
Wed Nov 12 04:24:12 EST 2003


Paul Miller wrote:

> Is there any particular good reason to inherit from
> exceptions.Exception?  I've never seen any code that depends on what
> the base class(es) of a raised exception is (are).
> 
> My use case is in a game I am writing.  The code for my Game class
> contains the following:
> 
> class Game (object):
> 
>     def start (self):
>         try:
>             self.players[1]
>         except IndexError:
>             raise NotEnoughPlayers
> 
> where NotEnoughPlayers is really just an empty classic class suitable
> for raising.  Is there any benefit to importing exceptions and
> inheriting from exceptions.Exception, other than maybe theoretical
> purity?

Besides the advantage, already pointed out to you, that "except X,x:"
catches all exceptions of any subclass of X (not just of class X itself),
you do get a small but useful amount of "machinery" from class
Exception:

>>> class X(Exception): pass
...
>>> try: raise X(23)
... except Exception, e: print 'error', e
...
error 23

i.e., Exception subclasses may be instantiated with arguments and
their instances display those arguments when printed.


Alex





More information about the Python-list mailing list