zoukankan      html  css  js  c++  java
  • 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
  • 相关阅读:
    css !import
    算法
    java web 运动前端
    oauth 2
    js 优化
    js 代码优化 (写的可以)
    2015/08/17 《有两条均线,你应该注意》
    佳能相机操作 EDSDK 教程 C# 版本
    2015/8/14——了2000股,是否正确呢——明天待验证?
    系统架构师考试——程序计数器 PC, 指令寄存器IR、状态寄存器SR、通用寄存器GR
  • 原文地址:https://www.cnblogs.com/hailin2018/p/13036157.html
Copyright © 2011-2022 走看看