概述
开发过程中一般都会使用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.
type (异常类别)
get the exception type of the exception being handled (a class object)
value (异常说明,可带参数)
get the exception parameter (a class instance)
traceback (traceback对象,包含更丰富的信息)
get a traceback object which encapsulates the call stack at the point where the exception originally occurred (a traceback object)
其中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
最后
以上就是高兴棒棒糖为你收集整理的python traceback对象_Python异常处理-traceback和exc_info的全部内容,希望文章能够帮你解决python traceback对象_Python异常处理-traceback和exc_info所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
发表评论 取消回复