5
votes

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

1

1 Answers

10
votes

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).