Search code examples
pythonexceptionscopefinallytry-except

why is exception argument not caught by finally block in python


try:
    ...
except (SomeError) as err:
    ...
else:
    ...
finally:
    if err:
   ...

This gives an error: 'err not defined'. Because the exception argument - err - is not defined as far as the finally block is concerned. It appears then that the exception argument is local to the exception block.

You can get round it by copying err to another variable defined outside the block:

teleport = ""
try:
    ...
except (SomeError) as err:
    teleport = err
else:
    ...
finally:
    if teleport:
        ...

But why can't you simply reference the exception argument in the finally block? (Assuming I've not overlooked something else.)


Solution

  • try blocks will execute code that could possibly raise an exception. except block will execute the moment an exception is raised. The else block executes if no except is raised, and the finally block is executed no matter what.

    There is no point in checking for an exception in the finally block when you can just do that in the else block.

    Aside from that, the variable was likely garbage collected at the end of execution of the except block. It's similar to what happens with with blocks. This is why you can't do if err: