Why does `finally: return` not apply to an unhandled exception?

Why does the function not throw an exception? Apparently he is not caught.

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

print(f())  # ok
+4
source share
4 answers

This is clearly explained in the documentation :

If an exception occurs in any of the sentences and is not processed, the exception is temporarily saved. The offer is being executed finally. [..] If finallythe statement is executed by returnor break, the stored exception is discarded

+7
source

From docs :

, try.

@deceze

finally , , .

:

>>> try:
...     raise Exception
... finally:
...     print('yes')
... 
yes
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
Exception

, , "" , . ​​

+4

:

finally , try, . [...] finally " " , try break, continue return statement.

, finally, . :

def f():
    try:
        return 'OK'
    finally:
        return 'Finally'

f() # returns 'Finally'
+3

:

finally , try, . try except ( except else), finally .

, finally, finally, .

+2

All Articles