Python 獲取異常(Exception)信息的幾種方法
異常信息的獲取對(duì)于程序的調(diào)試非常重要,可以有助于快速定位有錯(cuò)誤程序語(yǔ)句的位置。下面介紹幾種 Python 中獲取異常信息的方法,這里獲取異常(Exception)信息采用 try…except… 程序結(jié)構(gòu)。
如下所示:
try: print(x)except Exception as e: print(e)1. str(e)
返回字符串類型,只給出異常信息,不包括異常信息的類型,如:
try: print(x)except Exception as e: print(str(e))
打印結(jié)果:
name ’x’ is not defined2. repr(e)
給出較全的異常信息,包括異常信息的類型,如:
try: print(x)except Exception as e: print(repr(e))
打印結(jié)果:
NameError('name ’x’ is not defined',)
一般情況下,當(dāng)我們知道異常信息類型后,可以對(duì)異常進(jìn)行更精確的捕獲,如:
try: print(x)except NameError: print(’Exception Type: NameError’)except Exception as e: print(str(e))3. 采用 traceback 模塊
需要導(dǎo)入 traceback 模塊,此時(shí)獲取的信息最全,與 Python 命令行運(yùn)行程序出現(xiàn)錯(cuò)誤信息一致。
用法:使用 traceback.print_exc() 或 traceback.format_exc() 打印錯(cuò)誤。
區(qū)別:traceback.print_exc() 直接打印錯(cuò)誤,traceback.format_exc() 返回字符串。
示例如下:
import tracebacktry: print(x)except Exception as e: traceback.print_exc()
等價(jià)于:
import tracebacktry: print(x)except Exception as e: msg = traceback.format_exc() print(msg)
打印結(jié)果都是:
Traceback (most recent call last): File 'E:/study/python/get_exception.py', line 4, in <module> print(x)NameError: name ’x’ is not defined
traceback.print_exc() 還可以接受 file 參數(shù)直接寫入到一個(gè)文件。比如:
# 寫入到 tb.txt 文件中traceback.print_exc(file=open(’tb.txt’,’w+’))
以上就是Python 獲取異常(Exception)信息的幾種方法的詳細(xì)內(nèi)容,更多關(guān)于python 獲取異常信息的資料請(qǐng)關(guān)注好吧啦網(wǎng)其它相關(guān)文章!
相關(guān)文章:
1. 前端html+css實(shí)現(xiàn)動(dòng)態(tài)生日快樂(lè)代碼2. XML 非法字符(轉(zhuǎn)義字符)3. 關(guān)于html嵌入xml數(shù)據(jù)島如何穿過(guò)樹(shù)形結(jié)構(gòu)關(guān)系的問(wèn)題4. vue實(shí)現(xiàn)復(fù)制文字復(fù)制圖片實(shí)例詳解5. XML基本概念XPath、XSLT與XQuery函數(shù)介紹6. CSS3實(shí)例分享之多重背景的實(shí)現(xiàn)(Multiple backgrounds)7. XML入門的常見(jiàn)問(wèn)題(三)8. el-input無(wú)法輸入的問(wèn)題和表單驗(yàn)證失敗問(wèn)題解決9. 不要在HTML中濫用div10. XML入門的常見(jiàn)問(wèn)題(四)
