笔记-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 ---- 包含调用栈信息的对象。

 

posted @ 2019-01-03 12:17  木林森__𣛧  阅读(608)  评论(0编辑  收藏  举报