美文网首页Python语法糖
Python中获取异常(Exception)信息

Python中获取异常(Exception)信息

作者: 画星星高手 | 来源:发表于2018-06-18 16:02 被阅读37次

前言

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

try:

  ...

except Exception, e:

  ...

1、str(e)

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

'integer division or modulo by zero'

2、repr(e)

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

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

3、e.message

获得的信息同str(e)

4、采用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 '########################################################'

运行结果

image.png image.png

参考资料

https://www.cnblogs.com/klchang/p/4635040.html

相关文章

  • Python中获取异常(Exception)信息

    前言 异常信息的获取对于程序的调试非常重要,可以有助于快速定位有错误程序语句的位置。下面介绍几种python中获取...

  • 异常捕获

    异常的类型:Exception(内建异常类)python中的异常都是继承自这个Exception而来的

  • python 异常

    异常 在python中,我们用异常对象表示错误信息,一般是Exception类或者是其子类的实例。当遇到错误时,程...

  • Python中的异常处理(不定时更新)

    1 异常的定义 程序运行期检测到的错误被称为异常exception,它以错误信息的形式展现。python提供了异常...

  • python 自定义异常类

    python允许程序员自定义异常,用于描述python中没有涉及的异常情况,自定义异常必须继承Exception类...

  • 12.15

    一、python 异常exception except exception as err: 程序的原子性:一些不想...

  • C++异常

    异常处理 头文件中定义了异常类exception和bad_exception,异常类exce...

  • Python中的Singal和Exception

    概述 python是如何处理中断信号Singal的? python中的异常(Exception)分为哪几种,不同E...

  • 异常信息的获取

    异常信息的获取对于程序的调试非常重要,可以有助于快速定位有错误程序语句的位置。下面介绍几种python中获取异常信...

  • Python - 异常(Exception)

    异常的捕捉与raise

网友评论

    本文标题:Python中获取异常(Exception)信息

    本文链接:https://www.haomeiwen.com/subject/truneftx.html