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 individual 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With