Exception Handling and Inheritance

Franz GEIGER fgeiger at datec.at
Wed Dec 27 12:31:00 EST 2000


Thank you, Robert,

in the meanwhile I had an other idea:

def Formatted(self):
    try:
        return "Exception '%d' (%s) in '%s'" % (self.iCode, self.sInfo,
self.sSource)
    except:
        return str(self.args)

Exception.Formatted = Formatted    # !!!

class TException(Exception):
    :
    :

class TException_Data(TException):
    :
    :

This would make Exception.Formatted() act like __str__ and polymorphically
call the Formatted() method on derived classes in situations like this:

except Exception, e:
    :
    :

So now there's only one handler at all even if I raise my TException.


> Exception as a catch all since it tends to mask programming errors. Of

Admitted.


Thanks and best regards
Franz GEIGER


"Robert Roy" <rjroy at NO-SPAM.magma.ca> wrote in message
news:806k4tc5t9js74aqv81u214ijiqsni9q2j at 4ax.com...
> 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