[Tutor] Subclassing Exceptions

Chris Fuller cfuller084 at thinkingplanet.net
Sat Jan 7 04:24:40 CET 2012


I had an interesting experience today.

Python 2.7.1 (r271:86832, Nov 28 2010, 19:31:37) 
[GCC 4.4.5] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> class Foo(Exception):
...  def __init__(self, a,b,c):
...   self.args = (a,b,c)
... 
>>> raise Foo(1,2,3)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
__main__.Foo: (1, 2, 3)
>>> class Foo(SyntaxError):
...  def __init__(self, a,b,c):
...   self.args = (a,b,c)
... 
>>> raise Foo(1,2,3)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
__main__.Foo: None


Inheriting from SyntaxError doesn't work!  When I create a new exception, I 
generally subclass from the built-in exception it most resembles, in case 
there was some reason to also catch it via an ancestor.  But I'm not sure if 
that is really all that useful an idea in practice.  How do you folk do it?

By the way, inheriting from StandardError, the direct ancestor of  
SyntaxError, works as expected, and its parent is Exception.

Cheers


More information about the Tutor mailing list