Custom exceptions -- inherit from exceptions.Exception?
aleax at aleax.it
Wed Nov 12 10:24:12 CET 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):
> 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
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
>>> class X(Exception): pass
>>> try: raise X(23)
... except Exception, e: print 'error', e
i.e., Exception subclasses may be instantiated with arguments and
their instances display those arguments when printed.
More information about the Python-list