Skip to content
Advertisement

“except” statement with same exception class as parameter twice

In Python, how can I use except block with same exception name twice in try/except statements without need to wrap code into one more try/except block?

Simple example (here each call of pages.get may raise the exception):

JavaScript

For now, in my Django app I do handling like this (but I don’t want “extra” try block here):

JavaScript

Any handling code better than above is appreciated! :)

Thanks.

Advertisement

Answer

You can’t do this either and expect the elif to execute:

JavaScript

And there’s no reason to do this, really. Same for your except concern.

Here’s the disassembled Python bytecode of your first code snippet:

JavaScript

It’s obvious that the first COMPARE_OP to NameError (at offset 17) will catch the exception and jump to after the second such comparison (at offset 36).

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement