zoukankan      html  css  js  c++  java
  • Python中获取异常(Exception)信息

      异常信息的获取对于程序的调试非常重要,可以有助于快速定位有错误程序语句的位置。下面介绍几种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):	', str(Exception)
        print 'str(e):		', str(e)
        print 'repr(e):	', repr(e)
        print 'e.message:	', e.message
        print 'traceback.print_exc():'; traceback.print_exc()
        print 'traceback.format_exc():
    %s' % traceback.format_exc()
    print '########################################################'
    print '
    ########################################################'  
    print "i = int('a') Exception Info"
    print '---------------------------------------------------------'
    try:
        i = int('a')
    except Exception, e:
        print 'str(Exception):	', str(Exception)
        print 'str(e):		', str(e)
        print 'repr(e):	', repr(e)
        print 'e.message:	', e.message
        print 'traceback.print_exc():'; traceback.print_exc()
        print 'traceback.format_exc():
    %s' % traceback.format_exc()
    print '########################################################' 

    示例结果

    补充 1(更新于2020.8.1)

    对于 Python 3 的 Exception,与 Python 2 的 Exception 相比,有两个需要注意的地方:

    1)在 Python 3 Exception 的 except 子句中,不支持使用逗号 ',' 分隔 Exception 和 e,所以需要采用 as 关键词进行替换;

    2)与 Python 2 Exception 类相比,Python 3 Exception 类没有 message 成员变量。针对这个问题,可以采用 sys.exc_info() 方法获取得到相关的异常信息。以 1/0 异常处理为例,更新的程序如下:

    import sys
    import traceback
    
    print('########################################################')
    print("1/0 Exception Info")
    print('---------------------------------------------------------')
    try:
        1/0
    except Exception as e:
        print('str(Exception):	', str(Exception))
        print('str(e):		', str(e))
        print('repr(e):	', repr(e))
        # Get information about the exception that is currently being handled  
        exc_type, exc_value, exc_traceback = sys.exc_info() 
        print('e.message:	', exc_value)
        print("Note, object e and exc of Class %s is %s the same." % 
                  (type(exc_value), ('not', '')[exc_value is e]))
        print('traceback.print_exc(): ', traceback.print_exc())
        print('traceback.format_exc():
    %s' % traceback.format_exc())
    print('########################################################')

    注:

    1) sys.exc_info() 方法可以获取正在处理的异常信息,即 except 子句正在处理的异常,其返回值为一个tuple类型的三元组(exc_type, exc_value, exc_traceback),其中,exc_type为获取到的异常类型;exc_value为该异常类型对象;exc_traceback为一个 traceback 对象,包含异常最初发生的调用栈信息。

    2) as 关键字以及 sys.exc_info() 方法对于 Python 2 同样适用。

    3) 程序中的变量 e 和 exc_value 是同一个异常类型实例对象。

    参考资料:

    Getting the exception value in Python

  • 相关阅读:
    springMVC 返回json 忽略类中属性的注解
    MySQL中函数CONCAT及GROUP_CONCAT
    ArrayList转成HashMap再转成LinkedHashMap 自己的解决方案
    easyui datebox 设置不可编辑
    js或jquery如何获取父级、子级、兄弟元素(包括祖级、孙级等)
    关于js中空值比较和传值的问题
    Tomcat报错:Failed to start component [StandardEngine[Catalina].StandardHost[localhost]]
    JQuery 阻止js事件冒泡 阻止浏览器默认操作
    visualstudio2017 +EF+Mysql生成实体数据模型闪退
    MVC错误:查询的结果不能枚举多次
  • 原文地址:https://www.cnblogs.com/klchang/p/4635040.html
Copyright © 2011-2022 走看看