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

0dminnimda
  • 1,242
  • 3
  • 12
  • 29

1 Answers1

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

chepner
  • 497,756
  • 71
  • 530
  • 681
  • 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 07 '20 at 19:27