Python2,3中获取异常信息--str,repr 和 traceback

python 中使用 try…except…程序结构获取异常信息,如下所示:

try:
  ...
except Exception as e:
  ...

1、str,repr、traceback 的用法

1、str(e)
返回字符串类型,只给出异常信息,不包括异常信息的类型,如1/0的异常信息
‘division by zero’
2、repr(e)
给出较全的异常信息,包括异常信息的类型,如1/0 的异常信息
“ZeroDivisionError(‘division by zero’)”
3、采用 traceback 模块
需要导入 traceback 模块,此时获取的信息最全,与 python 命令行运行程序出现错误信息一致。使用 traceback.print_exc() 打印异常信息到标准错误,就像没有获取一样,或者使用 traceback.format_exc() 将同样的输出获取为字符串。也可以向这些函数传递各种各样的参数来限制输出,或者重新打印到像文件类型的对象。

try:
    1/0
except Exception as e:
    print('str(e):\t', str(e))
    print("repr(e):\t", repr(e))

在这里插入图片描述

import traceback

try:
    1/0
except Exception as e:
    print('traceback.print_exc():\n%s' % traceback.print_exc())

在这里插入图片描述

import traceback

try:
    1/0
except Exception as e:
    print('traceback.format_exc():\n%s' % traceback.format_exc())

在这里插入图片描述

2、python2、3 中的区别

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

python2 中支持如下写法,python3 不支持

try:
  ...
except Exception, e:
  ...

(2)python2 中有 e.message 的用法,获得的信息同str(e)
使用如下:

try:
    1/0
except Exception as e:
    print("e.message:", e.message)

执行结果:

('e.message:', 'integer division or modulo by zero')

Python 3 Exception 类没有 message 成员变量,python23 切换的时候,为了兼容同一换成 str(e)。

猜你喜欢

转载自blog.csdn.net/happyjacob/article/details/109439672