Things on this page are fragmentary and immature notes/thoughts of the author. Please read with your own judgement!
Tips and Traps¶
- The
finally
statements are guaranteed to be executed (presuming no power outage or anything outside of Python's control) after atry
/except
block runs even ifreturn
,break
orcontinue
is used in atry
/except
block. This mean that a if afinally
block presents the function won't exit immediate on reaching areturn
statement in atry
/except
block. Instead, the function will wait until thefinally
block is executed to exit. If anotherreturn
statement is run in thefinally
block, the previous return value is overwritten. This means that you should never use areturn
/yield
statement in afinally
block.
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 [ ]: