Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 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?

like image 731
user225312 Avatar asked Jun 01 '11 10:06

user225312


1 Answers

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
like image 114
Ignacio Vazquez-Abrams Avatar answered Sep 25 '22 12:09

Ignacio Vazquez-Abrams