Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't `finally: return` propagate an unhandled exception? [duplicate]

Why does the function not raise the exception? It's apparently not caught.

def f():
    try:
        raise Exception
    finally:
        return "ok"

print(f())  # ok
like image 863
planetp Avatar asked Dec 05 '22 00:12

planetp


2 Answers

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 the finally clause executes a return or break statement, the saved exception is discarded

like image 77
deceze Avatar answered Dec 06 '22 12:12

deceze


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.

like image 37
Maroun Avatar answered Dec 06 '22 14:12

Maroun