返回吃异常 [英] return eats exception
问题描述
我发现以下行为至少是奇怪的:
I found the following behavior at least weird:
def errors():
try:
ErrorErrorError
finally:
return 10
print errors()
# prints: 10
# It should raise: NameError: name 'ErrorErrorError' is not defined
当您使用在
。这是一个bug吗?这是否记录在任何地方?最终
子句中返回
The exception disappears when you use return
inside a finally
clause. Is that a bug? Is that documented anywhere?
但真正的问题(和我将标记为正确的答案)是:
什么是python开发人员的原因允许这种奇怪的行为?
But the real question (and the answer I will mark as correct) is:
What is the python developers' reason to allow that odd behavior?
推荐答案
您询问了Python开发人员的推理。我不能为他们说话,但没有其他行为是有道理的。函数可以返回值,也可以引发异常;它不能做到这两个。 finally子句的目的是提供保证的清理代码,无论异常如何。通过在finally子句中放置return语句,您已经声明要返回值,无论什么,无论如何。如果Python的行为正如你所提出的那样提出异常,那么它将违反finally子句的合同(因为它不会返回你所要求返回的值)。
You asked about the Python developers' reasoning. I can't speak for them, but no other behavior makes sense. A function can either return a value, or it can raise an exception; it can't do both. The purpose of a "finally" clause is to provide cleanup code that is "guaranteed" to be run, regardless of exceptions. By putting a return statement in a finally clause, you have declared that you want to return a value, no matter what, regardless of exceptions. If Python behaved as you are asking and raised the exception, it would be breaking the contract of the "finally" clause (because it would fail to return the value you told it to return).
这篇关于返回吃异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!