1. 程式人生 > >筆記-python異常信息輸出

筆記-python異常信息輸出

情況下 onerror except turned rom 返回值 per 字符串 案例

筆記-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 ---- 包含調用棧信息的對象。

筆記-python異常信息輸出