Exception Handling and Inheritance

Robert Roy rjroy at NO-SPAM.magma.ca
Wed Dec 27 17:54:05 CET 2000

On Sat, 23 Dec 2000 10:45:57 +0100, "Franz GEIGER" <fgeiger at datec.at>

>I'd like to specialize Exceptions. So I derived a TException from Exception
>and added all the things I think I need to have.
>But now there is a problem: I have created a second branch in the
>inheritance tree:
>    StandardError
>        IOError
>        ...
>    TException
>        TDataException
>        ...
>When I want to catch TExceptions I write
>    obj.meth(anyStuff)
>except TException, e:
>    print >> sys.stderr, "Panic: %s!" % e.Formatted()
>But what about Exceptions? They are not caught by my TException handler! And
>Exception does not have my Formatted method.

You could always add __str__ = Formatted to your class definintion
since the published interface to Exception supports the str()

Then  you could write 
except Exception, e:
    print >> sys.stderr, "Panic:", e

Since TException is derived from Exception this would work.

>Do I really have to catch them in a 2nd handler? Or can I add some
>functionality somehow to Exception instead of implementing it in a derived

As Aahz mentionned, it is usually considered a Bad Idea to use
Exception as a catch all since it tends to mask programming errors. Of
course you could always Exception then do:
if e.__class__ == AException:
	handle a
elif e.__class__ == TException:
	handle t

but this does not really improve your lot in life over multiple

>Many thanks in advance and best regards


More information about the Python-list mailing list