subclassing Exceptions

Quinn Dunkan quinn at
Sun Jul 22 22:26:41 CEST 2001

On Sun, 22 Jul 2001 18:36:07 GMT, Sheila King <sheila at> wrote:
>I'm trying to see the "big picture". I'm a "big picture" kind of gal. I
>don't feel comfortable working with just bits and pieces...just enough
>information (in the information-giver's opinion) for me to get by.
>If I want to really understand subclassing Exceptions, and whether or
>not I would ever want to override any of the standard exception classes
>methods or such, then I need to understand how those exceptions work.
>Like I said, I've been working (a bit) so far with subclassing
>, and for me, I needed to read the source code of that module
>and see how it worked. Then *bing* a light went off in my head, I
>understood, and I could proceed.
>Does this mean there is something wrong with me? Should I be satisfied
>with the docs only?
>Someone else gave me a good suggestion on the Tutor List, that if I was
>really interested in how the Exception class works, I should grab the
>source for Python 1.5.2, before the exception class code was written in
>C. I might do that, but this discussion (and another on the Tutor List)
>has helped immensely, and I may be fine from here.

Yeah, go find  You'll probably realize that you knew the big
picture all along: exceptions are just normal instances of normal classes, and
they "work" exactly the same.  They have a few __getitem__ and __str__ hacks
to be compatible from when exceptions were just strings (and maybe tuples),
but they're just normal classes.  You can subclass Exception if you want, all
that means is a) you inherit Exception's methods, and b) 'except Exception'
will catch your exception.  Or you could not inherit.  Or you could raise some
random other object (not recommended, though).  Exceptions are instantiated
and used just like any other object:

class Foo:
    def __init__(self, x, y, z=10):
        self.x, self.y, self.z = x, y, z
    def foo(self):
        print self.x

    raise Foo(10, 4, z=40)
except Foo, e:
    print e.z

# let's be perverse:
    import smtplib
    raise smtplib.SMTP('')
except smtplib.SMTP, s:
    s.sendmail('me', ['you'], 'hi')


This also raises the question: when types and classes are unified, will you be
able to raise anything?

More information about the Python-list mailing list