日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

python-try-except:pass的用法及說明_python

作者:半島鐵盒@ ? 更新時間: 2023-01-20 編程語言

python-try-except:pass用法

1.為了跳過for循環里的某次循環

以下代碼當某次循環發生錯誤時,執行except代碼塊,continue跳過該次循環:

for i in range(x):
? ? try:
? ? ? ? i += 1
? ? ? ? print(i)
? ? except:
? ? ? ? continue

2.還可以寫成這樣

遇到錯誤執行except代碼塊,pass忽略錯誤并繼續往下運行,略有不同的就是無論程序錯誤與否都會運行到continue這一行代碼:

for i in range(x):
? ? try:
? ? ? ? i += 1
? ? ? ? print(i)
? ? except:
? ? ? ? pass
? ? continue

3.還有一種用法

就是遇到錯誤時直接中斷整個for循環:

try:
? ? for i in range(x):
? ? ? ? i += 1
? ? ? ? print(i)
except:
? ? pass

總之try+except就是當try的從屬代碼執行遇到錯誤時,中斷try從屬代碼并執行except的從屬語句

python try: pass except:pass流程控制

import socket
def aa():
? ? try:
? ? ? ? s=socket.socket()
? ? ? ? s.bind('8.8.8.8')

? ? ? ? bb()

? ? except TypeError as e:
? ? ? ? return -1

def bb():

? ? try:
? ? ? ? socket.bind('8.8.8.8')
? ? except AttributeError as e:
? ? ? ? return -2
? ??
print(aa())


#得出的aa()的返回值是-1,說明aa()函數錯誤就會拋出異常,不會走bb()函數
#經實驗得到,當aa()函數未錯誤時,bb()函數書寫錯誤,會走bb()函數拋出的異常
#aa()函數和bb()函數均被故意書寫錯誤,是為了拋出異常

總結

原文鏈接:https://blog.csdn.net/weixin_45556441/article/details/110733362

欄目分類
最近更新