traceback: make you more flexibility to handle exceptions in python

abnormal

异常在python中是屡见不鲜了,程序在执行到某一行代码时,发现有问题,比如数组索引越界,变量没有定义啊等等,此时就会抛出异常

Catch the exception

在python,一般都是使用try···except来对异常进行捕获

try:
    1 / 0
except Exception as e:
    print(e)  # division by zero

然而仅仅只有这些也看不出什么东西来,我们需要知道在哪一行代码引发的异常。

大家在程序报错的时候,会经常看到报错信息如下

Traceback (most recent call last):

Traceback What the hell is this? In fact, this is the python traceback information about the program being given, from an object called a traceback object, and this object is a traceback object by sys.exc_info () to get the


traceback objects

import sys


try:
    1 / 0
except Exception as e:
    print(e)  # division by zero
    exc_type, exc_value, exc_tb = sys.exc_info()
    print(exc_type)  # <class 'ZeroDivisionError'>
    print(exc_value)  # division by zero
    print(exc_tb)  # <traceback object at 0x0000000009F484C8>

We can see, sys.exc_info () Gets the exception of the information currently being processed, and returns a tuple. The first element of the tuple type is abnormal, the second element value is abnormal value, the abnormality information is third traceback object. print (e) printing is an abnormal value.

With us you can print the traceback object traceback and format of information


traceback module


接收一个tracebackobject

import sys
import traceback


try:
    1 / 0
except NameError as e:
    exc_type, exc_value, exc_tb = sys.exc_info()
    traceback.print_tb(exc_tb)
"""
File "C:/Users/EDZ/Desktop/satori/wtfpython/1.py", line 6, in <module>
    1 / 0
"""

# 如果我们不捕获异常看看输出啥?
"""
Traceback (most recent call last):
  File "C:/Users/EDZ/Desktop/satori/wtfpython/1.py", line 6, in <module>
    1 / 0
ZeroDivisionError: division by zero
"""
# 可以看到最后一行的ZeroDivisionError则是异常类型,division by zero则是异常值。中间的则是我们的traceback object

However, in addition traceback object, print_tb may also receive two parameters

  • limit

    比如我们在调用C函数出现了异常,但我们是先调用A函数,在A函数里面调用B函数,在B函数里面调用C函数,limit参数则是限制stack trace的层级的,如果为None也就是不指定,那么会打印所有层级

    import sys
    import traceback
    
    
    def C():
        1 / 0
    
    def B():
        C()
    
    def A():
        B()
    
    
    try:
        A()
    except Exception as e:
        exc_type, exc_value, exc_tb = sys.exc_info()
        traceback.print_tb(exc_tb)
        """
          File "C:/Users/EDZ/Desktop/satori/wtfpython/1.py", line 16, in <module>
            A()
          File "C:/Users/EDZ/Desktop/satori/wtfpython/1.py", line 12, in A
            B()
          File "C:/Users/EDZ/Desktop/satori/wtfpython/1.py", line 9, in B
            C()
          File "C:/Users/EDZ/Desktop/satori/wtfpython/1.py", line 6, in C
            1 / 0
        """
    
        traceback.print_tb(exc_tb, limit=2)
        """
          File "C:/Users/EDZ/Desktop/satori/wtfpython/1.py", line 16, in <module>
            A()
          File "C:/Users/EDZ/Desktop/satori/wtfpython/1.py", line 12, in A
            B()
        """
  • file

    可以指定file,输出到某个文件里,默认是sys.stderr


与print_tb相比多了两个参数,需要传入exc_type,exc_value,exc_tb,也就是sys.exc_info返回的三个值。与print_tb相比,打印信息多了开头的Traceback (most recent call last):,以及最后一行的异常类型和value信息。还有一个不同是当异常为SyntaxError时,会有"^"来指示语法错误的位置

import sys
import traceback


def C():
    1 / 0

def B():
    C()

def A():
    B()


try:
    A()
except Exception as e:
    exc_type, exc_value, exc_tb = sys.exc_info()
    traceback.print_exception(exc_type, exc_value, exc_tb)
"""
Traceback (most recent call last):
  File "C:/Users/EDZ/Desktop/satori/wtfpython/1.py", line 16, in <module>
    A()
  File "C:/Users/EDZ/Desktop/satori/wtfpython/1.py", line 12, in A
    B()
  File "C:/Users/EDZ/Desktop/satori/wtfpython/1.py", line 9, in B
    C()
  File "C:/Users/EDZ/Desktop/satori/wtfpython/1.py", line 6, in C
    1 / 0
ZeroDivisionError: division by zero
"""

You can see, the printed results and error information is the same.


和print_exception类似,只不过不需要我们手动的传入sys.exc_info返回的三个值,而是会自动帮我们调用

import sys
import traceback


def C():
    1 / 0

def B():
    C()

def A():
    B()


try:
    A()
except Exception as e:
    traceback.print_exc()
"""
Traceback (most recent call last):
  File "C:/Users/EDZ/Desktop/satori/wtfpython/1.py", line 16, in <module>
    A()
  File "C:/Users/EDZ/Desktop/satori/wtfpython/1.py", line 12, in A
    B()
  File "C:/Users/EDZ/Desktop/satori/wtfpython/1.py", line 9, in B
    C()
  File "C:/Users/EDZ/Desktop/satori/wtfpython/1.py", line 6, in C
    1 / 0
ZeroDivisionError: division by zero
"""

format_exc

和print_exc一样,只不过是以字符串的形式返回,需要我们自己手动打印

import sys
import traceback


def C():
    1 / 0

def B():
    C()

def A():
    B()


try:
    A()
except Exception as e:
    tb_info = traceback.format_exc()
    print(tb_info)
"""
Traceback (most recent call last):
  File "C:/Users/EDZ/Desktop/satori/wtfpython/1.py", line 16, in <module>
    A()
  File "C:/Users/EDZ/Desktop/satori/wtfpython/1.py", line 12, in A
    B()
  File "C:/Users/EDZ/Desktop/satori/wtfpython/1.py", line 9, in B
    C()
  File "C:/Users/EDZ/Desktop/satori/wtfpython/1.py", line 6, in C
    1 / 0
ZeroDivisionError: division by zero
"""

Guess you like

Origin www.cnblogs.com/traditional/p/11111314.html