return eats exception

后端 未结 4 2099
臣服心动
臣服心动 2020-11-28 10:44

I found the following behavior at least weird:

def errors():
    try:
        ErrorErrorError
    finally:
        return 10

print errors()
# print         


        
4条回答
  •  误落风尘
    2020-11-28 11:00

    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).

提交回复
热议问题