def func1():
try:
print 'try statement in func1. after this return 1'
return 1
finally:
print 'after the try statement in func1, return 2'
return 2
def func2():
try:
print 'raise a value error'
raise ValueError()
except:
print 'an error has been raised! return 1!'
return 1
finally:
print 'okay after all that let\'s return 3'
return 3
print func1()
print func2()
这将返回:
try statement in func1. after this return 1
after the try statement in func1, return 2
2
raise a value error
an error has been raised! return 1!
okay after all that let's return 3
3
def func1():
try:
return 1 # ignoring the return
finally:
return 2 # returns this return
def func2():
try:
raise ValueError()
except:
# is going to this exception block, but ignores the return because it needs to go to the finally
return 1
finally:
return 3
def func3():
return 0 # finds a return here, before the try except and finally block, so it will use this return
try:
raise ValueError()
except:
return 1
finally:
return 3
func1() # returns 2
func2() # returns 3
func3() # returns 0
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. A more complicated example (having except and finally clauses in the same try statement works as of Python 2.5):
预先放置
print
语句确实有助于:这将返回:
您会注意到python总是返回最后一个要返回的内容,而不管这两个函数中的代码“reached”
return 1
。一个
finally
块总是运行,因此在函数中返回的最后一件事是finally块中返回的任何内容。在func1
中,这是2。在func2
中,这是3。它总是指向
finally
块,因此它将忽略try
和except
中的return
。如果在try
和except
之上有一个return
,它将返回该值。来自Pythondocumentation
因此,一旦try/except块使用return离开,它会将返回值设置为给定的-finally块将始终execute,并应用于释放资源等,而在那里使用另一个return-覆盖原始块。
在您的特定情况下,
func1()
返回2
和func2()
返回3
,因为这些是finally块中返回的值。相关问题 更多 >
编程相关推荐