为什么Finally在return语句之后执行?
Why is Finally executed after return statement?
def Test():
try:
return 0
finally:
return 1
x = Test()
print(x)
为什么上面代码的输出是1?
https://code.hackerearth.com/5cc081y
尽管从逻辑上讲控件将函数留在 return 语句中。
https://docs.python.org/2/tutorial/errors.html
"A finally clause is always executed before leaving the try
statement, whether an exception has occurred or not. When an exception
has occurred in the try clause and has not been handled by an except
clause (or it has occurred in a except or else clause), it is
re-raised after the finally clause has been executed. 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
部分 总是 在离开 try
块之前执行。 return 0
将离开 try
块。所以 finally
部分首先执行, returns 1.
def Test():
try:
return 0
finally:
return 1
x = Test()
print(x)
为什么上面代码的输出是1? https://code.hackerearth.com/5cc081y 尽管从逻辑上讲控件将函数留在 return 语句中。
https://docs.python.org/2/tutorial/errors.html
"A finally clause is always executed before leaving the try statement, whether an exception has occurred or not. When an exception has occurred in the try clause and has not been handled by an except clause (or it has occurred in a except or else clause), it is re-raised after the finally clause has been executed. 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
部分 总是 在离开 try
块之前执行。 return 0
将离开 try
块。所以 finally
部分首先执行, returns 1.