python traceback模块使用 异常的获取与处理

 

 

1、traceback.print_exc()
2、traceback.format_exc()
3、traceback.print_exception()

简单说下这三个方法是做什么用的:

1、print_exc():是对异常栈输出
2、format_exc():是把异常栈以字符串的形式返回,print(traceback.format_exc()) 就相当于traceback.print_exc()
3、print_exception():traceback.print_exc()实现方式就是traceback.print_exception(sys.exc_info()),可以点sys.exc_info()进去看看实现

 

 

问题:traceback.print_exc()和traceback.format_exc()有什么区别呢?
format_exc()返回字符串,print_exc()则直接给打印出来。
即traceback.print_exc()与print traceback.format_exc()效果是一样的。
print_exc()还可以接受file参数直接写入到一个文件。比如
traceback.print_exc(file=open('tb.txt','w+'))
写入到tb.txt文件去。
 

traceback.print_exc([limit[, file]])

print_exception(sys.exc_type, sys.exc_value, sys.exc_traceback, limit, file)的简写

import traceback


def abc():
    try:
        1/0
    except Exception as e:
        traceback.print_exc()


if __name__ == '__main__':
    abc()

 

    1/0
ZeroDivisionError: division by zero

 

traceback.format_exc([limit])

类似于print_exc(limit), 但是返回字符串而不是输出到file.

import traceback


try:
    raise ValueError("msg")
except Exception as e:
    print(traceback.format_exc())

 

raise ValueError("msg")
ValueError: msg

 

traceback.print_exc()函数只是traceback.print_exception()函数的一个简写形式,而它们获取异常相关的数据都是通过sys.exc_info()函数得到的。

import sys
import traceback


def func(a, b):
    return a / b

if __name__ == '__main__':
    try:
        func(1, 0)
    except Exception as e:
        print('print_exception()')
        exc_type, exc_value, exc_tb = sys.exc_info()
        print('the exc type is:', exc_type)
        print('the exc value is:', exc_value)
        print('the exc tb is:', exc_tb)
        traceback.print_exception(exc_type, exc_value, exc_tb)

返回结果

print_exception()
Traceback (most recent call last):
the exc type is: <class 'ZeroDivisionError'>
  File , line 16, in <module>
the exc value is: division by zero
    func(1, 0)
the exc tb is: <traceback object at 0x000002583038D188>
  File , line 12, in func
    return a / b
ZeroDivisionError: division by zero

 

sys.exc_info()返回的值是一个元组,其中第一个元素,exc_type是异常的对象类型,exc_value是异常的值,exc_tb是一个traceback对象,对象中包含出错的行数、位置等数据。

然后通过print_exception函数对这些异常数据进行整理输出。

 

 

 

三种方式打印结果是一样的。在开发时,做调试是很方便的。也可以把这种异常栈写入日志。

logging.exception(ex)

# 指名输出栈踪迹, logging.exception的内部也是包了一层此做法
logging.error(ex, exc_info=1) 

# 更加严重的错误级别 
logging.critical(ex, exc_info=1) 

 

posted @ 2022-02-12 11:39  minger_lcm  阅读(1643)  评论(0编辑  收藏  举报