[Tutor] Subclassing Exceptions
Steven D'Aprano
steve at pearwood.info
Sat Jan 7 06:06:06 CET 2012
Devin Jeanpierre wrote:
>> 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 your error represents a value error, then yes they would.
But in that case, why should I subclass ValueError instead of just using
ValueError itself? Writing my own exceptions is only useful if I intend to
give the caller the *choice* of either treating my exception the same or
different from ValueError: that is, if my error is a more specific kind of
ValueError. If it is not a specific kind of value error, then just use the
generic built-in ValueError exception instead.
try:
x = some_function()
except MyValueError:
# treat my errors specially
except ValueError:
# any other kind of ValueError caught here
vs.
try:
x = some_function()
except ValueError:
# any kind of ValueError caught here, including MyValueError
The same goes for all exception types, although in practice I find that I
generally only subclass ValueError.
--
Steven
More information about the Tutor
mailing list