subclassing Exceptions

Erik Max Francis max at alcyone.com
Sun Jul 22 14:00:28 EDT 2001


Sheila King wrote:

> OK, interesting. I didn't realize you could make an exception without
> subclassing it.

You can, but the library reference (2.2, Built-in Exceptions) states
that user-defined exceptions _should_ be derived from
exceptions.Exception, and suggests that this behavior might be enforced
in the future.  It's generally good practice.

> However, I noticed earlier this evening, from browsing the
> exceptions.c
> source (as noted elsewhere in this thread), that the Exceptions seem to
> have 3 methods and 1 datamember, namely:
> 
> methods:
> __init__
> __getitem__
> __str__
> 
> and the datamember
> __doc__

And an `args' method, as the library reference states:

Python 2.0 (#2, Apr  4 2001, 19:28:30) 
[GCC egcs-2.91.66 19990314/Linux (egcs-1.1.2 release)] on linux2
Type "copyright", "credits" or "license" for more information.
>>> try:    
...  raise Exception
... except Exception, e:
...  pass
... 
>>> dir(e)
['args']

> So, I would imagine that if you subclass it, and do not specifically
> define these methods/data listed above, that you at least inherit them
> from the base class. Whereas, if you create an "exception" that does
> not
> derive from a base Exception class, it would not have these methods.

Correct.  A class you intend to use for exceptions is just like any
other class; there's nothing special about it.  Only when you derive
from exceptions.Exception does it make it clear you plan to use the
class for exception handling, and since you derive from the Exception
class you get standard behavior for free even if you do not extend it.

> Hmm...I just tried a little experiment in the interactive shell to see
> if I could confirm/deny my above theory, and it gave me surprising
> results that I do not understand, and which seem to indicate no
> difference between deriving it from an Exception class or not.

Well, if you don't understand the results, it's going to be a little
hard telling you what you did wrong or what you misunderstood without
knowing what you actually did.  :-)

-- 
 Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/
 __ San Jose, CA, US / 37 20 N 121 53 W / ICQ16063900 / &tSftDotIotE
/  \ History is a bucket of ashes.
\__/ Carl Sandburg
    Erik Max Francis' bookmarks / http://www.alcyone.com/max/links/
 A highly categorized list of Web links.



More information about the Python-list mailing list