Python中捕获异常信息

本文介绍了Python中多种捕获和处理异常的方法,包括使用str、repr和message属性获取异常信息,以及利用traceback模块进行详细错误追踪。


                             Python中捕获异常信息

异常信息的获取对于程序的调试非常重要,可以有助于快速定位有错误程序语句的位置。下面介绍几种python中获取异常信息的方法,这里获取异常(Exception)信息采用try...except...程序结构。如下所

复制代码

try:

 

  ...

 

except Exception,e:

 

  ...

复制代码

 

1str(e)

返回字符串类型,只给出异常信息,不包括异常信息的类型,如1/0的异常信

'integer division or modulo byzero'

2repr(e)

给出较全的异常信息,包括异常信息的类型,如1/0的异常信

"ZeroDivisionError('integerdivision or modulo by zero',)"

3e.message

获得的信息同str(e)

4、采用traceback

  需要导入traceback模块,此时获取的信息最全,与python命令行运行程序出现错误信息一致。使用traceback.print_exc()打印异常信息到标准错误,就像没有获取一样,或者使用traceback.format_exc()将同样的输出获取为字符串。你可以向这些函数传递各种各样的参数来限制输出,或者重新打印到像文件类型的对象

 

示例如下

复制代码

import traceback

 

print '########################################################'

print "1/0Exception Info"

print '---------------------------------------------------------'

try:

    1/0

except Exception,e:

    print 'str(Exception):\t',str(Exception)

    print 'str(e):\t\t', str(e)

    print 'repr(e):\t', repr(e)

    print 'e.message:\t', e.message

    print 'traceback.print_exc():';traceback.print_exc()

    print 'traceback.format_exc():\n%s' %traceback.format_exc()

print '########################################################'

print '\n########################################################' 

print "i =int('a') Exception Info"

print '---------------------------------------------------------'

try:

    i = int('a')

except Exception,e:

    print 'str(Exception):\t',str(Exception)

    print 'str(e):\t\t', str(e)

    print 'repr(e):\t', repr(e)

    print 'e.message:\t', e.message

    print 'traceback.print_exc():';traceback.print_exc()

    print 'traceback.format_exc():\n%s' %traceback.format_exc()

print '########################################################'

复制代码

 

示例结果

http://images0.cnblogs.com/blog2015/757205/201507/101018471117700.png

http://images0.cnblogs.com/blog2015/757205/201507/101020300189696.png

 

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值