def test1():
try:
print('to do stuff')
raise Exception('hehe')
print('to return in try')
return 'try'
except Exception:
print('process except')
print('to return in except')
return 'except'
finally:
print('to return in finally')
return 'finally'
test1Return = test1()
print('test1Return : ' + test1Return)
輸出:spa
to do stuff
process except
to return in except
to return in finally
test1Return : finallyio
def test2():
try:
print('to do stuff')
print('to return in try')
return 'try'
except Exception:
print('process except')
print('to return in except')
return 'except'
finally:
print('to return in finally')
return 'finally'
test2Return = test2()
print('test1Return : ' + test2Return)
to do stuff
to return in try
to return in finally
test2Return : finallytest
這裏在 try 中沒有拋出異常,所以不會轉到 except 中,可是在try 中遇到return時,也會當即強制轉到finally中執行,並在finally中返回exception
test1和test2獲得的結論:循環
不管是在try仍是在except中,遇到return時,只要設定了finally語句,就會中斷當前的return語句,跳轉到finally中執行,若是finally中遇到return語句,就直接返回,再也不跳轉回try/excpet中被中斷的return語句異常
def test3():
i = 0
try:
i += 1
print('i in try : %s'%i)
raise Exception('hehe')
except Exception:
i += 1
print('i in except : %s'%i)
return i
finally:
i += 1
print ('i in finally : %s'%i )
print('test3Return : %s'% test3())
輸出:di
i in try : 1
i in except : 2
i in finally : 3
test3Return : 2process
def test4():
i = 0
try:
i += 1
return i
finally:
i += 1
print ('i in finally : %s'%i )
print('test4Return : %s' % test4())
i in finally : 2
test4Return : 1co
test3和test4獲得的結論:background
在except和try中遇到return時,會鎖定return的值,而後跳轉到finally中,若是finally中沒有return語句,則finally執行完畢以後仍返回原return點,將以前鎖定的值返回(即finally中的動做不影響返回值),若是finally中有return語句,則執行finally中的return語句。
def test5():
for i in range(5):
try:
print('do stuff %s'%i)
raise Exception(i)
except Exception:
print('exception %s'%i)
continue
finally:
print('do finally %s'%i)
test5()
輸出
do stuff 0
exception 0
do finally 0
do stuff 1
exception 1
do finally 1
do stuff 2
exception 2
do finally 2
do stuff 3
exception 3
do finally 3
do stuff 4
exception 4
do finally 4
test5獲得的結論:
在一個循環中,最終要跳出循環以前,會先轉到finally執行,執行完畢以後纔開始下一輪循環