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
finally
clause is executed. [..] If thefinally
clause executes areturn
orbreak
statement, 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With