Exception Handling and Inheritance

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


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

>
>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:
>Exception
>    StandardError
>        IOError
>        ...
>    TException
>        TDataException
>        ...
>
>When I want to catch TExceptions I write
>try:
>    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()
function.

Then  you could write 
try:
    obj.meth(anyStuff)
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
>TException?

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
etc...

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

>
>Many thanks in advance and best regards
>Franz GEIGER
>
>

Bob



More information about the Python-list mailing list