13

Python 打印异常信息_获取异常类型_完整错误信息 - 文渊博客

 3 years ago
source link: https://www.wenyuanblog.com/blogs/python-get-the-exception-value.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Python 获取异常(Exception)信息

异常信息的获取对于程序的调试非常重要,可以有助于快速定位有错误程序语句的位置。下面介绍几种 Python 中获取异常信息的方法,这里获取异常(Exception)信息采用 try…except… 程序结构。

如下所示:

python
try: print(x) except Exception as e: print(e)

1. str(e)

返回字符串类型,只给出异常信息,不包括异常信息的类型,如:

python
try: print(x) except Exception as e: print(str(e))

打印结果:

name 'x' is not defined

2. repr(e)

给出较全的异常信息,包括异常信息的类型,如:

python
try: print(x) except Exception as e: print(repr(e))

打印结果:

NameError("name 'x' is not defined",)

一般情况下,当我们知道异常信息类型后,可以对异常进行更精确的捕获,如:

python
try: print(x) except NameError: print('Exception Type: NameError') except Exception as e: print(str(e))

3. 采用 traceback 模块

需要导入 traceback 模块,此时获取的信息最全,与 Python 命令行运行程序出现错误信息一致。

用法:使用 traceback.print_exc()traceback.format_exc() 打印错误。

区别:traceback.print_exc() 直接打印错误,traceback.format_exc() 返回字符串。

示例如下:

python
import traceback try: print(x) except Exception as e: traceback.print_exc()
python
import traceback try: print(x) except Exception as e: msg = traceback.format_exc() print(msg)

打印结果都是:

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 参数直接写入到一个文件。比如:

python
# 写入到 tb.txt 文件中 traceback.print_exc(file=open('tb.txt','w+'))

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK