Python Traceback模块:捕获更详细的异常信息

1、问题描述:

try....except抛出的异常信息太少,没有包含异常发生的具体位置,不方便排查。traceback库能极大的帮助我们,给出更详细的异常信息。

 

2、解决方法:

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()进去看看实现

 

3、举例说明:

测试代码:

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


if __name__ == '__main__':
    import sys
    import time
    import traceback

    try:
        func(1, 0)
    except Exception as e:
        print('***', type(e), e, '***')
        time.sleep(2)

        print("***traceback.print_exc():*** ")
        time.sleep(1)
        traceback.print_exc()
        time.sleep(2)

        print("***traceback.format_exc():*** ")
        time.sleep(1)
        print(traceback.format_exc())
        time.sleep(2)

        print("***traceback.print_exception():*** ")
        time.sleep(1)
        traceback.print_exception(*sys.exc_info())

运行结果:

 1 *** <class 'ZeroDivisionError'> division by zero ***
 2 
 3 
 4 ***traceback.print_exc():*** 
 5 Traceback (most recent call last):
 6   File "E:/HttpRunnerManager-jh/ApiManager/tests.py", line 42, in <module>
 7     func(1, 0)
 8   File "E:/HttpRunnerManager-jh/ApiManager/tests.py", line 33, in func
 9     return a / b
10 ZeroDivisionError: division by zero
11 
12 
13 ***traceback.format_exc():*** 
14 Traceback (most recent call last):
15   File "E:/HttpRunnerManager-jh/ApiManager/tests.py", line 42, in <module>
16     func(1, 0)
17   File "E:/HttpRunnerManager-jh/ApiManager/tests.py", line 33, in func
18     return a / b
19 ZeroDivisionError: division by zero
20 
21 
22 ***traceback.print_exception():*** 
23 Traceback (most recent call last):
24   File "E:/HttpRunnerManager-jh/ApiManager/tests.py", line 42, in <module>
25     func(1, 0)
26   File "E:/HttpRunnerManager-jh/ApiManager/tests.py", line 33, in func
27     return a / b
28 ZeroDivisionError: division by zero

 

上一篇:Flutter Crash Analytics(iOS)


下一篇:Redis集群概述