为什么“finally:return”不传播未处理的异常?

2024-03-28 11:45:40 发布

您现在位置:Python中文网/ 问答频道 /正文

为什么函数不引发异常?显然没有被抓住。你知道吗

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

print(f())  # ok

Tags: 函数returndefexceptionokraiseprinttry
3条回答

docs

A finally clause is always executed before leaving the try statement.

@deceze在他的answer中引用了更相关的部分

函数返回finally子句中的字符串,并且在返回后不会引发异常,这就是打印的内容。你知道吗

如果您尝试执行:

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

然后,如您所见,“yes”被打印出来,异常被抛出到print语句之后。你知道吗

这在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

documentation

A finally clause is always executedbefore 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.

也就是说,在一个函数中,finally子句总是返回。即使没有发生异常:

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

f() # returns 'Finally'

相关问题 更多 >