Why does the function not raise the exception? It's apparently not caught.
def f():
try:
raise Exception
finally:
return "ok"
print(f()) # ok
Why does the function not raise the exception? It's apparently not caught.
def f():
try:
raise Exception
finally:
return "ok"
print(f()) # ok
This is explicitly explained in the documentation:
If an exception occurs in any of the clauses and is not handled, the exception is temporarily saved. The
finallyclause is executed. [..] If thefinallyclause executes areturnorbreakstatement, the saved exception is discarded
From the docs:
A finally clause is always executed before leaving the try statement.
@deceze quoted the more relevant part in his answer
The function returns the string in the finally clause and doesn't raise the exception since it returned, and that what gets printed.
If you try to execute:
>>> try:
... raise Exception
... finally:
... print('yes')
...
yes
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
Exception
Then as you can see, "yes" is printed and the exception is thrown after the print statement.
From the documentation:
A finally clause is always executed before leaving the try statement, whether an exception has occurred or not. [...] The finally clause is also executed “on the way out” when any other clause of the try statement is left via a break, continue or return statement.
That mean, in a function the finally clause will always be the one that returns. Even if no exception as occurred:
def f():
try:
return 'OK'
finally:
return 'Finally'
f() # returns 'Finally'
The documentation says:
A finally clause is always executed before leaving the
trystatement, whether an exception has occurred or not. When an exception has occurred in thetryclause and has not been handled by anexceptclause (or it has occurred in aexceptorelseclause), it is re-raised after thefinallyclause has been executed.
In your case, the exception has not been handled, so should be re-raised after the finally clause, but since you return from the finally clause, the exception is never re-raised.