Differences between revisions 5 and 14 (spanning 9 versions)
Revision 5 as of 2003-09-07 11:16:23
Size: 1591
Editor: ip503dabc3
Comment:
Revision 14 as of 2004-12-28 21:50:26
Size: 2359
Editor: 212-32-244-232
Comment: super() only works for new-style classes
Deletions are marked like this. Additions are marked like this.
Line 2: Line 2:

I (LionKimbro) don't know much about writing exception classes; Here's hoping someone rewrites this better.
Line 12: Line 10:
        Exception.__init__(self)         Exception.__init__(self, 'Host Not Found exception: missing %s' % host)
Line 20: Line 18:
    raise HostNotFound( "taoriver.net" )
except HostNotFound, X:
    print "Host Not Found:", X.host
    raise HostNotFound("taoriver.net")
except HostNotFound, exc:
    # Handle exception.
    print exc # -> '
Host Not Found exception: missing taoriver.net'
    print exc
.host  # -> 'taoriver.net'
    
Line 25: Line 26:
== Overloading __str__ == == See Also ==
Line 27: Line 28:
You can overload {{{__str__}}} to get the exception to explain itself:

{{{
#!python
class HostNotFound(Exception):
    def __init__( self, host ):
        self.host = host
    def __str__( self ):
        return "Host Not Found exception: missing %s" % self.host
}}}

That way, you only need print the exception instance:

{{{
#!python
try:
    raise HostNotFound( "taoriver.net" )
except HostNotFound, X:
    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:''

{{{
#!python
class HostNotFound(Exception):
    def __init__(self, host):
        self.host = host
        Exception.__init__(self, 'Host Not Found exception: missing %s' % host)
}}}
HandlingExceptions, TracebackModule
Line 63: Line 33:
     * When you're logging exceptions, you want access to the traceback information to. After some research, I believe what you use is extract_tb or extract_stack from the traceback module. -- LionKimbro [[DateTime(2003-09-07T15:23:43Z)]]

  ''Look at cgitb for how to do detailed TB introspection, and as an example of why mixing logic and (HTML) layout is a very bad thing.''
Line 64: Line 38:

  ''AlexMartelli's "Dos and Don'ts".''

  * The new text involving {{{super}}} doesn't seem to work for me.

Using Python 2.3:

{{{
#!python
class LocalNamesSyntaxError(Exception):
    def __init__(self, msg):
        self.msg=msg
        super(LocalNamesSyntaxError, self)('Local Names v1.1 Syntax Error: %s' % msg)
}}}

{{{
Traceback (most recent call last):
  File "parser.py", line 92, in ?
    pprint.pprint(parse_text(test_string))
  File "parser.py", line 69, in parse_text
    cursor=parse_record_type(cursor,line,results)
  File "parser.py", line 43, in parse_record_type
    raise LocalNamesSyntaxError("unrecognized v1.1 record type- require LN, NS, X, or PATTERN")
  File "parser.py", line 17, in __init__
    super(LocalNamesSyntaxError, self)('Local Names v1.1 Syntax Error: %s' % msg)
TypeError: super() argument 1 must be type, not classobj
}}}

Is this a Python2.4 v. Python2.3 thing? Or is there a simple error in my code? -- LionKimbro

super() only works for new-style classes. Exception is still an old-style class: type 'classobj'. I've fixed the example. -- JohannesGijsbers

Writing Exception Classes

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, 'Host Not Found exception: missing %s' % host)

You may later write:

   1 try:
   2     raise HostNotFound("taoriver.net")
   3 except HostNotFound, exc:
   4     # Handle exception.
   5     print exc  # -> 'Host Not Found exception: missing taoriver.net'
   6     print exc.host  # -> 'taoriver.net'

See Also

HandlingExceptions, TracebackModule

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?

    • When you're logging exceptions, you want access to the traceback information to. After some research, I believe what you use is extract_tb or extract_stack from the traceback module. -- LionKimbro DateTime(2003-09-07T15:23:43Z)

    Look at cgitb for how to do detailed TB introspection, and as an example of why mixing logic and (HTML) layout is a very bad thing.

  • What better exception-foo is out there?

    AlexMartelli's "Dos and Don'ts".

  • The new text involving super doesn't seem to work for me.

Using Python 2.3:

   1 class LocalNamesSyntaxError(Exception):
   2     def __init__(self, msg):
   3         self.msg=msg
   4         super(LocalNamesSyntaxError, self)('Local Names v1.1 Syntax Error: %s' % msg)

Traceback (most recent call last):
  File "parser.py", line 92, in ?
    pprint.pprint(parse_text(test_string))
  File "parser.py", line 69, in parse_text
    cursor=parse_record_type(cursor,line,results)
  File "parser.py", line 43, in parse_record_type
    raise LocalNamesSyntaxError("unrecognized v1.1 record type- require LN, NS, X, or PATTERN")
  File "parser.py", line 17, in __init__
    super(LocalNamesSyntaxError, self)('Local Names v1.1 Syntax Error: %s' % msg)
TypeError: super() argument 1 must be type, not classobj

Is this a Python2.4 v. Python2.3 thing? Or is there a simple error in my code? -- LionKimbro

super() only works for new-style classes. Exception is still an old-style class: type 'classobj'. I've fixed the example. -- JohannesGijsbers

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.