7

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?

3 Answers 3

10

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
Sign up to request clarification or add additional context in comments.

4 Comments

But why catch the derived one at all, when the base can handle everything?
Because you may want to handle the derived exception in a different way from the base exception.
But if I don't want to handle the specific exception in a different way, is using the base exception class all right?
Absolutely. All derived exceptions are also instances of the base exception.
3

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.

1 Comment

Note that I never said a bare except clause. I am asking about the difference between catching the BaseError which is the base class vs the FooError which is more generalized.
2

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.

2 Comments

Thanks for your answer, please see my comment in Ignacio's answer.
@A A: No problem; @Ignacio beat me to it

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.