Your search query "linkto%3A%22WritingExceptionClasses%22" didn't return any results. Please change some terms and refer to HelpOnSearching for more information.
(!) Consider performing a full-text search with your search terms.

Clear message

Writing Exception Classes

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

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

You may later write:

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

See Also

HandlingExceptions, TracebackModule


Using Python 2.3:

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

Traceback (most recent call last):
  File "", line 92, in ?
  File "", line 69, in parse_text
  File "", line 43, in parse_record_type
    raise LocalNamesSyntaxError("unrecognized v1.1 record type- require LN, NS, X, or PATTERN")
  File "", 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

Thanks a lot, I was having hardtime figureing this out, as exactly the same construct worked in other places. -- HariDara

It might become a 2.4 vs 2.5 thing though, as 2.5 should allow new-style classes.

Don't forget the method name after super; it doesn't magically assume __init__. (fixed above) -kcarnold

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