網站首頁 編程語言 正文
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
相關推薦
- 2022-10-29 C#?CLR學習?C++使用namespace實例詳解_C 語言
- 2022-07-01 python讀取nc數據并繪圖的方法實例_python
- 2022-08-10 pandas.DataFrame.iloc的具體使用詳解_python
- 2023-02-10 docker的鏡像存放地址在哪里_docker
- 2023-07-16 oracle 創建定時任務
- 2022-11-27 MobLink?Android?快速集成指南_Android
- 2022-02-25 image-webpack-loader 報錯 Invalid regular expression
- 2022-10-13 解析React中useMemo與useCallback的區別_React
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支