Python 通过traceback追溯异常信息

Python 通过traceback追溯异常信息

在这里插入图片描述

  1. 导入traceback包

    import traceback
    
  2. 自定义函数

    def func_3():
        return 1 / 0
    
    
    def func_2():
        func_3()
    
    
    def func_1():
        func_2()
    
  3. 捕捉异常

    try:
        func_1()
    except Exception as e:
        traceback_info = traceback.format_exc()
        print("===traceback_info===")
        print(traceback_info)
        print("===traceback_info===")
    
    

    打印追溯异常信息:

    ===traceback_info===
    Traceback (most recent call last):
      File "C:\Users\15011\AppData\Local\Temp\ipykernel_15680\2442583961.py", line 13, in <module>
        func_1()
      File "C:\Users\15011\AppData\Local\Temp\ipykernel_15680\2442583961.py", line 10, in func_1
        func_2()
      File "C:\Users\15011\AppData\Local\Temp\ipykernel_15680\2442583961.py", line 6, in func_2
        func_3()
      File "C:\Users\15011\AppData\Local\Temp\ipykernel_15680\2442583961.py", line 2, in func_3
        return 1 / 0
    ZeroDivisionError: division by zero
    
    ===traceback_info===
    

你可能感兴趣的:(Python,python,traceback,追溯异常信息)