I never really use finally, so I wanted to test a few things before using it more regularly. I noticed that when running:
def f():
try:
1/0
# 1/1
except:
print('except') # 1
raise # 2
finally:
print('finally') # 3
try:
f()
except:
print("haha")
we get this order of execution:
except
finally
haha
What is the rule for the order of excution?
From what I see I get this rule:
- run everything in the
exceptblock, but not theraisestatement, if any such statement is present - run the
finallyblock - go back to the
exceptblock, and run the lastraisestatement, if present
Is that correct?
Are there other statements than raise in an except block that can be postponed after the finally block?
>Solution :
According to [Python.Docs]: Errors and Exceptions – Defining Clean-up Actions (emphasis is mine, read all the bullets though):
- …
- An exception could occur during execution of an except or else clause. Again, the exception is re-raised after the finally clause has been executed.
- …
So that’s the expected behavior.