2

I recently discovered some odd behavior when writing a Python program. I have situation like follows:

try:
    raise Exception("Meh!")
except Exception as e:
    print e

if e:
    print e

To my surprise, this prints "Meh!" twice, showing that the exception 'e' is still accessible, even after the try/except block has ended.

My question is whether this is intended behavior of python or more a coincidence. Can I count on this to always work or is this not the official behavior?

I am aware of that I can just add another variable to capture this, like this:

my_exception = None
try:
    raise Exception("Meh!")
except Exception as e:
    print e
    my_exception = e

if my_exception:
    print my_exception

But if the first version is not considered a hack, I am leaning towards, because it would mean having fewer variables.

Btw. I am using python 2.7.6.

Thanks

helgar
  • 121
  • 1
  • I wouldn't consider it to be a duplicate, as the linked question is about variable assignments within `try`, but the answers don't address a name bound by the `except` clause, which might be something slightly different. – Petr Mar 18 '15 at 16:31

1 Answers1

2

Try/except blocks do not create a new scope in Python, which is why you can still use e after the block. (This answer has more information about scopes in Python.)

However, if an exception is not raised, e will never be created, so you can't later do if e without an UnboundLocalError occurring.

Community
  • 1
  • 1
mipadi
  • 398,885
  • 90
  • 523
  • 479