python traceback对象_Python异常处理-traceback和exc_info

开发过程中一般都会使用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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值