why is exception argument not caught by finally block in python

111 views Asked by At
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.)

2

There are 2 answers

7
Zizouz212 On BEST ANSWER

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:

5
hspandher On

You cannot access just because exception is not raised and so variable is not defined, hence the undefined variable error. Besides there is no point in dealing with exception in your final block, you should do that stuff in except block itself.