编程

Python异常处理-traceback和exc_info

2016-03-13  本文已影响2635人  知识分子中的文盲

开发过程中一般都会使用traceback将捕获到的异常打印出来。

import traceback

def fake_exception():
    1 / 0

def catch_exception():
    try:
        fake_exception()
    except:
        traceback.print_exc()

catch_exception()

结果

Traceback (most recent call last):
  File ".\test.py", line 9, in catch_exception
    fake_exception()
  File ".\test.py", line 5, in fake_exception
    1 / 0
ZeroDivisionError: integer division or modulo by zero

事实上,traceback里的所有信息都是从exc_info里面获取的。
traceback.print_exc([limit[, file]])
In fact, it uses sys.exc_info() to retrieve the same information in a thread-safe way instead of using the deprecated variables.

那么我们再来看一下exc_info()这个方法。
https://docs.python.org/2/library/sys.html?highlight=sys#module-sys
该方法返回三个值:type, value, traceback.

其中traceback中还包含了更为丰富的信息,比如文件名,行号等等。如果觉得系统默认的traceback打印格式不好看的话,可以利用exc_info的返回值自定义格式。

import sys

def fake_exception():
    1 / 0

def catch_exception():
    try:
        fake_exception()
    except:
        e_type, e_value, e_traceback = sys.exc_info()
        print "type ==> %s" % (e_type.__name__)
        print "value ==> %s" %(e_value.message)
        print "traceback ==> file name: %s" %(e_traceback.tb_frame.f_code.co_filename)
        print "traceback ==> line no: %s" %(e_traceback.tb_lineno)
        print "traceback ==> function name: %s" %(e_traceback.tb_frame.f_code.co_name)

catch_exception()

结果显示

type ==> typename: ZeroDivisionError
value ==> message: integer division or modulo by zero
traceback ==> fielname: .\test.py
traceback ==> lineno: 8
traceback ==> name: catch_exception
上一篇下一篇

猜你喜欢

热点阅读