python异常处理可以消除异常本身_Python异常处理 - 行号

这篇博客介绍了如何在Python中使用sys和traceback模块来获取错误发生的行号和堆栈信息。通过示例代码展示了在发生IndexError异常时,如何打印出详细的错误跟踪信息,包括错误发生的具体行号、堆栈跟踪以及不同方式的错误输出格式。
摘要由CSDN通过智能技术生成

要简单地得到行号,您可以使用sys,如果您想要更多,请尝试traceback模块。

import sys

try:

[][2]

except IndexError:

print 'Error on line {}'.format(sys.exc_info()[-1].tb_lineno)

打印:

Error on line 3

import sys, traceback

def lumberjack():

bright_side_of_death()

def bright_side_of_death():

return tuple()[0]

try:

lumberjack()

except IndexError:

exc_type, exc_value, exc_traceback = sys.exc_info()

print "*** print_tb:"

traceback.print_tb(exc_traceback, limit=1, file=sys.stdout)

print "*** print_exception:"

traceback.print_exception(exc_type, exc_value, exc_traceback,

limit=2, file=sys.stdout)

print "*** print_exc:"

traceback.print_exc()

print "*** format_exc, first and last line:"

formatted_lines = traceback.format_exc().splitlines()

print formatted_lines[0]

print formatted_lines[-1]

print "*** format_exception:"

print repr(traceback.format_exception(exc_type, exc_value,

exc_traceback))

print "*** extract_tb:"

print repr(traceback.extract_tb(exc_traceback))

print "*** format_tb:"

print repr(traceback.format_tb(exc_traceback))

print "*** tb_lineno:", exc_traceback.tb_lineno

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值