In Python 3.6, returning from a finally
block squashes all unhandled exceptions - Why?
Example:
def foo():
print("Inside foo")
raise ValueError("No good values supplied")
print("Unreachable in foo")
def bar():
print("Inside bar")
try:
foo()
print("Unreachable in bar")
finally:
print("Finally block")
return "A value"
print("Starting process")
res = bar()
print(f"Should be unreachable, because error is not handled - {res}")
If the finally
block doesn't return, the exception is correctly propagated up the stack
This question is different to Weird Try-Except-Else-Finally behavior with Return statements, which is asking about the order of resolution of except
blocks, because it is a construct that explicitly does not handle exceptions raised in the try
part of the code. A naieve reading of the code, with an understanding of Python tenets, such as "explicit is better than implicit" would lead a developer not seeing this type of construct before to conclude that when an exception is raised in the try
block, the finally would run, but the return
would have no effect as the exception is unhandled and therefore would raise. The reality is, though, the exception is instead implicitly handled and the function returns successfully to the calling code