[Tutor] Subclassing Exceptions
Devin Jeanpierre
jeanpierreda at gmail.com
Sat Jan 7 05:42:49 CET 2012
> 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?
If somebody wanted to catch a ValueError, would they also mean to
catch my error? (The same with SyntaxError and so on). Probably not.
If they would, then I raise the relevant exception. It is very
possible to accidentally catch the wrong thing if you put too much in
a try block, and I don't like making that any easier.
-- Devin
On Fri, Jan 6, 2012 at 10:24 PM, Chris Fuller
<cfuller084 at thinkingplanet.net> wrote:
> 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
> _______________________________________________
> Tutor maillist - Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
More information about the Tutor
mailing list