日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

python try catch finally执行顺序_对python中的try、except、finally 执行顺序详解

發布時間:2023/12/19 python 28 豆豆
生活随笔 收集整理的這篇文章主要介紹了 python try catch finally执行顺序_对python中的try、except、finally 执行顺序详解 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

如下所示:

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 stuff

process except

to return in except

to return in finally

test1Return : 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 stuff

to return in try

to return in finally

test2Return : finally

這里在 try 中沒有拋出異常,因此不會轉到 except 中,但是在try 中遇到return時,也會立即強制轉到finally中執行,并在finally中返回

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

輸出:

i in try : 1

i in except : 2

i in finally : 3

test3Return : 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 : 2

test4Return : 1

test3和test4得到的結論:

在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執行,執行完畢之后才開始下一輪循環

總結

以上是生活随笔為你收集整理的python try catch finally执行顺序_对python中的try、except、finally 执行顺序详解的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。