1. 程式人生 > >筆記-python異常資訊輸出

筆記-python異常資訊輸出

筆記-python異常資訊輸出

 

1.      異常資訊輸出

python異常捕獲使用try-except-else-finally語句;

 

在except 語句中可以使用except as e,然後通過e得到異常資訊;

 

  1. str(e): # 返回字串型別,只給出異常資訊,不包括異常資訊的型別,如I/O的異常資訊。

division by zero

  1. repr(e): #給出較全的異常資訊,包括異常資訊的型別

ZeroDivisionError('division by zero',)

  1. e.message #資訊最為豐富,一般情況下使用這個選項就足夠了
  2. traceback# 獲取資訊最全

 

2.      traceback

 

This module provides a standard interface to extract, format and print stack traces of Python programs. It exactly mimics the behavior of the Python interpreter when it prints a stack trace. This is useful when you want to print stack traces under program control, such as in a “wrapper” around the interpreter.

 

The module uses traceback objects — this is the object type that is stored in the sys.last_traceback variable and returned as the third item from sys.exc_info().

 

比較常用的方法有:

print_exception(etype, value, tb [ ,limit [,file ] ])

 

print_exc([limit [ , file ] ]) # 它是一個print_exception的簡寫,列印資訊

format_exc() # 與print_exc類似,但它返回一個字串,而不是列印

 

 

案例程式碼:

import traceback
import sys

class Myex_ValueError(Exception):
    """
    my exception
    """
   
def __init__(self, msg):
        self.message = msg


try:
    a = 5
    b = 5/0
    raise Myex_ValueError('error')
except Exception as e:
    #print(e)
    #print(str(e))
    #print(repr(e))
    #print(e.__class__)
    #print(e.message)
    #traceback.print_exc()
   
print(traceback.format_exc())
    #traceback.print_stack()

 

3.      sys

上面提到了traceback會生成traceback 物件,而這個物件可以通過sys.exc_info()得到。

sys.exc_info()的返回值是一個tuple, (type, value/message, traceback)

這裡的type ---- 異常的型別

value/message ---- 異常的資訊或者引數

traceback ---- 包含呼叫棧資訊的物件。