Things on this page are fragmentary and immature notes/thoughts of the author. Please read with your own judgement!
Tips and Traps¶
- The
finallystatements are guaranteed to be executed (presuming no power outage or anything outside of Python's control) after atry/exceptblock runs even ifreturn,breakorcontinueis used in atry/exceptblock. This mean that a if afinallyblock presents the function won't exit immediate on reaching areturnstatement in atry/exceptblock. Instead, the function will wait until thefinallyblock is executed to exit. If anotherreturnstatement is run in thefinallyblock, the previous return value is overwritten. This means that you should never use areturn/yieldstatement in afinallyblock.
In [7]:
def f1():
try:
print("Beginning of the try block (before return) ...")
return 1
print("End of the try block (after return) ...")
except:
return 2
else:
return 3
finally:
print("Beginning of the finally block (before return) ...")
return -1
print("end of the finally block (after return) ...")
f1()
Out[7]:
In [8]:
def f2():
try:
raise RuntimeError
except:
print("Beginning of the exception block (before return) ...")
return 1
print("End of the exception block (after return) ...")
else:
return 2
finally:
print("Beginning of the finally block (before return) ...")
return -1
print("end of the finally block (after return) ...")
f2()
Out[8]:
In [10]:
def f3():
try:
raise RuntimeError
except:
print("Beginning of the exception block (before return) ...")
return 1
print("End of the exception block (after return) ...")
else:
return 2
finally:
print("The finally block is run.")
f3()
Out[10]:
In [ ]: