For any possible try-finally block in Python, is it guaranteed that the finally
block will always be executed?
For example, let’s say I return while in an except
block:
try:
1/0
except ZeroDivisionError:
return
finally:
print("Does this code run?")
Or maybe I re-raise an Exception
:
try:
1/0
except ZeroDivisionError:
raise
finally:
print("What about this code?")
Testing shows that finally
does get executed for the above examples, but I imagine there are other scenarios I haven't thought of.
Are there any scenarios in which a finally
block can fail to execute in Python?
finally
fail to execute or "defeat its purpose" is during an infinite loop,sys.exit
or a forced interrupt. The documentation states thatfinally
is always executed, so I'd go with that.finally
will not execute if the power cord is ripped from the wall.sys.exit
does nothing but throw an exception. Quite the misnomer.