In my Python script I would like to catch an exception, perform some cleanup operations, and raise
the exception again. Since the cleanup is common for both the success and failure paths, I tried putting it in the finally
block. However, when I add a return
statement inside the finally
block, the raise
is negated.
Here is an example (I am using Python 3.6.5):
def test():
try:
raise Exception('TEST')
except:
raise
finally:
print('FINALLY!')
return ''
if __name__ == '__main__':
test()
print('SHOULD NOT REACH THIS LINE!')
Any idea why it is happening?
This is addressed directly in the docs .
On one side:
- An exception could occur during execution of an
except
orelse
clause. Again, the exception is re-raised after thefinally
clause has been executed.
BUT :
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.