pythonにおけるtry,except,finallyの実行順序

7442 ワード

 
 
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)

出力:
to do stuffprocess exceptto return in exceptto return in finallytest1Return : finally
 
tryでraiseに異常があると、すぐにexceptに移行して実行し、exceptでreturnに遭遇した場合、強制的にfinallyに移行して実行し、finallyでreturnに遭遇した場合に戻る
 
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 stuffto return in tryto return in finallytest2Return : finally
ここではtryに異常は投げ出されていないのでexceptには移動しませんが、tryでreturnに遭遇した場合、すぐにfinallyに強制的に移動して実行し、finallyで戻ります.
test 1とtest 2で得られた結論:
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())

出力:
i in try : 1i in except : 2i in finally : 3test3Return : 2
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 : 2test4Return : 1
test 3とtest 4で得られた結論:
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 0exception 0do finally 0do stuff 1exception 1do finally 1do stuff 2exception 2do finally 2do stuff 3exception 3do finally 3do stuff 4exception 4do finally 4
test 5で得られた結論:
1つのループで、最終的にループから飛び出す前にfinally実行に移動し、実行が完了してから次のループを開始します.
転載先:https://www.cnblogs.com/ybwang/p/4738621.html