helgar
helgar

Reputation: 121

Python exceptions leaving local scope?

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

Upvotes: 2

Views: 283

Answers (1)

mipadi
mipadi

Reputation: 410672

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.

Upvotes: 2

Related Questions