久久r热视频,国产午夜精品一区二区三区视频,亚洲精品自拍偷拍,欧美日韩精品二区

您的位置:首頁(yè)技術(shù)文章
文章詳情頁(yè)

Python 獲取異常(Exception)信息的幾種方法

瀏覽:4日期:2022-07-01 08:41:42

異常信息的獲取對(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)文章!

標(biāo)簽: Python 編程
相關(guān)文章:
主站蜘蛛池模板: 县级市| 吐鲁番市| 佛山市| 巫山县| 禄劝| 浙江省| 祁阳县| 巩留县| 泾川县| 荣昌县| 兴国县| 上杭县| 镇赉县| 哈巴河县| 九龙坡区| 安国市| 库伦旗| 电白县| 防城港市| 宝应县| 古丈县| 延庆县| 鞍山市| 贺州市| 陇川县| 黔西| 杨浦区| 招远市| 射阳县| 阿城市| 东海县| 海兴县| 青铜峡市| 昌黎县| 财经| 玉屏| 井冈山市| 无锡市| 长治市| 吴川市| 榆中县|