Python中获取异常(Exception)信息

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

try:

  ...

except Exception, e:

  ...

 

一、str(e)函数

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

'integer division or modulo by zero'命令行

二、repr(e)调试

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

"ZeroDivisionError('integer division or modulo by zero',)"orm

三、e.message对象

得到的信息同str(e)blog

四、采用traceback模块字符串

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

 

示例以下:

import traceback

print '########################################################'
print "1/0 Exception 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 '########################################################' 

 

示例结果

 

参考资料:

Getting the exception value in Python

相关文章
相关标签/搜索