简体   繁体   中英

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

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:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM