6

why does this code not work?

def test():   
    e = None
    try:
        raise Exception

    except Exception as e:
        pass

    return e

test()

I get this error:

UnboundLocalError: local variable 'e' referenced before assignment

0

1 Answer 1

11

When an exception is caught and bound to a name, the name is cleared following the try statement. From the documentation of the try statement:

except E as N:
    foo

behaves the same as

except E as N:
    try:
        foo
    finally:
        del N

So if an exception is caught, e no longer exists once return e has been reached. This is described as being done to break the reference cycle between the stack frame (which contains a reference to e) and the traceback referenced by e (which contains a reference to the stack frame).

1
  • 5
    Outstanding answer. This shows me how many little things and details are still unknown for me as regards to how Python is implemented.
    – revliscano
    Jun 7, 2020 at 19:27

Not the answer you're looking for? Browse other questions tagged or ask your own question.