python嵌套try...except如何使用詳解
引言
眾所周知,在python中我們用try…except…來捕獲異常,使用raise來拋出異常,但是多重的try…except…是如何使用的呢
前提
拋出異常
當(dāng)調(diào)用raise
進行拋出錯誤的時候,拋出錯誤的后面的代碼不執(zhí)行
def func(): print("hello") raise Exception("出現(xiàn)了錯誤") print("world") func()
打印的錯誤堆棧
如果抓取錯誤,就相當(dāng)于if...else
,并不會打斷代碼的執(zhí)行
def func(): try: print("hello") raise Exception("出現(xiàn)了錯誤") 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,除非要對每一特殊異常進行特殊處理。
總結(jié)
到此這篇關(guān)于python嵌套try...except如何使用的文章就介紹到這了,更多相關(guān)python嵌套try...except使用內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
用python監(jiān)控服務(wù)器的cpu,磁盤空間,內(nèi)存,超過郵件報警
這篇文章主要介紹了如果用python監(jiān)控服務(wù)器的cpu,磁盤空間,內(nèi)存,超過郵件報警,幫助大家更好的理解和使用python,感興趣的朋友可以了解下2021-01-01