網站首頁 編程語言 正文
引言
眾所周知,在python中我們用try…except…來捕獲異常,使用raise來拋出異常,但是多重的try…except…是如何使用的呢
前提
拋出異常
當調用raise
進行拋出錯誤的時候,拋出錯誤的后面的代碼不執行
def func(): print("hello") raise Exception("出現了錯誤") print("world") func()
打印的錯誤堆棧
如果抓取錯誤,就相當于if...else
,并不會打斷代碼的執行
def func(): try: print("hello") raise Exception("出現了錯誤") except Exception as why: print(why) print("world") func()
自定義異常
自定義異常需要我們繼承異常的類,包括一些框架中的異常的類,我們自定義異常的話都需要繼承他們
class MyError(Exception): pass def say_hello(str): if str != "hello": raise MyError("傳入的字符串不是hello") print("hello") say_hello("world")
異常對象
- Exception 是多有異常的父類,他會捕獲所有的異常
- 其后面會跟一個as as后面的變量就是異常對象,異常對象是異常類實例化后得到的
多重try
如果是嵌套的try...except...的話,這一層raise的錯誤,會被上一層的try...except...進行捕獲
補充:捕獲異常的小方法
方法一:捕獲所有異常
a=10 b=0 try: print (a/b) except Exception as e: print(Exception,":",e) finally: print ("always excute")
運行:
<class 'Exception'> : division by zero
always excute
方法二:采用traceback模塊查看異常
import traceback try: print ('here1:',5/2) print ('here2:',10/5) print ('here3:',10/0) except Exception as e: traceback.print_exc()
運行:
here1: 2.5
here2: 2.0
Traceback (most recent call last):
? File "/Users/lilong/Desktop/online_release/try_except_use.py", line 59, in <module>
? ? print ('here3:',10/0)
ZeroDivisionError: division by zero
方法三:采用sys模塊回溯最后的異常
import sys try: print ('here1:',5/2) print ('here2:',10/5) print ('here3:',10/0) except Exception as e: info=sys.exc_info() print (info[0],":",info[1])
運行:
here1: 2.5
here2: 2.0
<class 'ZeroDivisionError'> : division by zero
注意:萬能異常Exception
被檢測的代碼塊拋出的異常有多種可能性,并且我們針對所有的異常類型都只用一種處理邏輯就可以了,那就使用Exception,除非要對每一特殊異常進行特殊處理。
總結
原文鏈接:https://blog.csdn.net/youhebuke225/article/details/124365365
相關推薦
- 2022-06-06 手機網頁問題解決方案點擊事件有陰影
- 2022-05-11 python?DataFrame的shift()方法的使用_python
- 2022-06-01 關于nginx?反向代理?URL替換方案_nginx
- 2022-07-28 Python常用Web框架Django、Flask與Tornado介紹_python
- 2022-11-12 C++設計與實現ORM系統實例詳解_C 語言
- 2022-06-07 victoriaMetrics代理性能優化問題解析_數據庫其它
- 2022-03-16 .net?6項目實現壓縮發布_實用技巧
- 2022-07-29 Ceph分布式存儲集群Pool資源池簡介及使用小結_其它綜合
- 最近更新
-
- 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同步修改后的遠程分支