Custom exceptions -- inherit from exceptions.Exception?

Mike C. Fletcher mcfletch at rogers.com
Wed Nov 12 02:22:41 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).
>  
>
I see it all the time:

try:
    blah()
except Exception, err: # want to get err object here...
    doSomethingToErr( err ) # e.g. log, or add extra data to the 
exception instance
    raise

Having all exceptions part of the main tree works very nicely for that 
kind of thing.
...

>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?
>  
>
Just as a note, you only have to do this:

class NotEnoughPlayers( Exception ):
    pass

as Exception is in the __builtin__ module.

The "theoretical purity" comes at a fairly low cost, and gives quite a 
bit back IMO.  Going even a step further and organising the errors you 
raise into a reasonable hierarchy, (preferably using standard exceptions 
as base-classes) is often likely to pay dividends as well, but that's 
another kettle of Cod.

Enjoy,
Mike

_______________________________________
  Mike C. Fletcher
  Designer, VR Plumber, Coder
  http://members.rogers.com/mcfletch/








More information about the Python-list mailing list