[Python-ideas] Improving Catching Exceptions

Steven D'Aprano steve at pearwood.info
Thu Jun 22 16:55:33 EDT 2017

On Thu, Jun 22, 2017 at 10:30:57PM +0200, Sven R. Kunze wrote:
> Hi folks,
> just one note I'd like to dump here.
> We usually teach our newbies to catch exceptions as narrowly as 
> possible, i.e. MyModel.DoesNotExist instead of a plain Exception. This 
> works out quite well for now but the number of examples continue to grow 
> where it's not enough.

(1) Under what circumstances is it not enough?

(2) Is that list growing?

(3) You seem to be implying that "catch narrow exceptions" is bad advice 
and we should catch Exception instead. How does that help?

> There are at least three examples I can name off the top of my head:
> 1) nested StopIteration - PEP 479

StopIteration and generators have been around a long time, since Python 
2.2 I think, so this is not new. To the extent this was a problem, it is 
fixed now.

> 2) nested ImportError
> 3) nested AttributeError

Both of those have been around since Python 1.x days, so not new either.

If the list is growing, can you give some more recent examples?

> 1) is clear. 2) usually can be dealt with by applying the following pattern:
> try:
>     import user
> except ImportError:
>     import sys
>     if sys.exc_info()[2].tb_next:
>         raise

I've never needed to write something like that for ImportError. It seems 
like an anti-pattern to me: sometimes it will silently swallow the 
exception, and now `user` will remain undefined, a landmine waiting to 
explode (with NameError) in your code.

> Chris showed how to deal with 3). Catching nested exception is not what 
> people want many times.

Isn't it? Why not? Can you explain further?

> Am I the only one getting the impression that there's a common theme here?

I don't know what common theme you see. I can't see one.

Do you actually have a proposal?


More information about the Python-ideas mailing list