当我放入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块处理异常,然后引发它。在
如果没有发生异常,则返回值。在
谢谢你的回答!太快了:)
这是因为您在
finally
块中放置了return
语句。这意味着您确实希望返回一个值,即使抛出异常也是如此。有关详细信息,请参见here。
Here是引用文档相关部分的答案:
另外,我不太明白你到底想达到什么目的;正如zmbq链接的顶部答案所指出的,你不可能两者兼得。
相关问题 更多 >
编程相关推荐