Differences between revisions 4 and 5
Revision 4 as of 2003-09-06 19:51:18
Size: 1196
Editor: dsl254-010-130
Comment: Exceptions derive from exception. Need call parent initializer?
Revision 5 as of 2003-09-07 11:16:23
Size: 1591
Editor: ip503dabc3
Comment:
Deletions are marked like this. Additions are marked like this.
Line 5: Line 5:
Derive Exception classes from Exception: Exception classes are not special, you just derive them from Exception:
Line 12: Line 12:
        Exception.__init__(self)
Line 13: Line 14:

  ''Do we call {{{Exception.__init__( self )}}}..?'' -- LionKimbro [[DateTime(2003-09-06T19:51:18Z)]]
Line 51: Line 50:
''In this instance, there's no need to overload {{{__str__}}}, as the standard Exception already has a {{{__str__}}} method:''

{{{
#!python
class HostNotFound(Exception):
    def __init__(self, host):
        self.host = host
        Exception.__init__(self, 'Host Not Found exception: missing %s' % host)
}}}
Line 53: Line 62:
  * How do you relay the traceback information?   * How do you relay the traceback information? ''Relay the traceback information? Moving it higher up the call-stack? Could you try to explain your question?''

Writing Exception Classes

I (LionKimbro) don't know much about writing exception classes; Here's hoping someone rewrites this better.

Exception classes are not special, you just derive them from Exception:

   1 class HostNotFound(Exception):
   2     def __init__( self, host ):
   3         self.host = host
   4         Exception.__init__(self)

You may later write:

   1 try:
   2     raise HostNotFound( "taoriver.net" )
   3 except HostNotFound, X:
   4     print "Host Not Found:", X.host

Overloading __str__

You can overload __str__ to get the exception to explain itself:

   1 class HostNotFound(Exception):
   2     def __init__( self, host ):
   3         self.host = host
   4     def __str__( self ):
   5         return "Host Not Found exception: missing %s" % self.host

That way, you only need print the exception instance:

   1 try:
   2     raise HostNotFound( "taoriver.net" )
   3 except HostNotFound, X:
   4     print X

I don't know if this is a good idea or not.

In this instance, there's no need to overload __str__, as the standard Exception already has a __str__ method:

   1 class HostNotFound(Exception):
   2     def __init__(self, host):
   3         self.host = host
   4         Exception.__init__(self, 'Host Not Found exception: missing %s' % host)

Questions

  • How do you relay the traceback information? Relay the traceback information? Moving it higher up the call-stack? Could you try to explain your question?

  • What better exception-foo is out there?

WritingExceptionClasses (last edited 2011-05-16 19:13:51 by VPN-18-101-8-113)

Unable to edit the page? See the FrontPage for instructions.