Deciding which exceptions to catch in Python
Suppose that I am using a library X
that specifies for example that exception.BaseError
is the base class for all exceptions of X
.
Now, there is another exception, say X.FooError
, which of course inherits from exception.BaseError
but is more generalized, let's say that it handles invalid input. Let's suppose there are many other such classes, inherting from BaseError
but all for generalized cases.
X
|
BaseError
|
FooError
So I want to then check for invalid input. So which exception should I catch? Of course, catching each indiv开发者_开发问答idual exception is not possible, so I catch the X.BaseError
and then print an error message. Or I can catch the X.FooError
specifically but then I miss out all the other error cases.
Is this the standard way of doing it -- catch the base exception? If yes, then why do the other exceptions exist? For the generalized case when we want to catch a specific exception?
Catch only the exceptions you can handle. If you can handle both the base exception and the derived exception then catch both. But make sure to put the derived exception first, since the first exception handler found that matches is the one used.
try:
X.foo()
except X.FooError:
pass
except X.BaseError:
pass
As usual, there is good advice in PEP-8, Style Guide for Python Code:
When catching exceptions, mention specific exceptions whenever possible instead of using a bare
except:
clause.
There's lots more in there, but it's pointless me reproducing it here.
In this case, I would catch the specifics, were I to handle them differently to a BaseError
and the BaseError
for those that require more general handling. I would stop well short of catching the built-in Exception
, however.
You catch a specfic exception by defining it in the except
clause, thus:
try:
#do stuff
except X.FooError:
# handle the error
except (X.AnotherError, x.YetAnotherError), exc:
print 'I'm handling %s' % exc
Notice you can handle multiple exception classes by listing them in a tuple.
精彩评论