对于“finally”claus,重读异常不起作用

2024-09-30 12:24:57 发布

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

当我放入finally子句时,except中的raise语句不起作用。在

因此except块不会生成Exception。在

我错过了什么?如果我想在finally子句返回值之后重新引发Exception,我需要怎么做?在

def test():
    res = 1
    try:
            raise Exception
            res = 2
    except:
            print('ha fallado')
            raise

    finally:
            return res
test()

解决方案

^{pr2}$

这样,如果发生异常,except块处理异常,然后引发它。在

如果没有发生异常,则返回值。在

谢谢你的回答!太快了:)


Tags: testreturndefexceptionres语句raiseprint
2条回答

这是因为您在finally块中放置了return语句。这意味着您确实希望返回一个值,即使抛出异常也是如此。

有关详细信息,请参见here

Here是引用文档相关部分的答案:

The try clause is executed, including any except and else clauses. If an exception occurs in any of the clauses and is not handled, the exception is temporarily saved. The finally clause is executed. If there is a saved exception it is re-raised at the end of the finally clause. If the finally clause raises another exception, the saved exception is set as the context of the new exception. If the finally clause executes a return or break statement, the saved exception is discarded:

>>> def f():
...     try:
...         1/0
...     finally:
...         return 42
...
>>> f()
42

另外,我不太明白你到底想达到什么目的;正如zmbq链接的顶部答案所指出的,你不可能两者兼得。

相关问题 更多 >

    热门问题