python exception信息_Python 异常信息获取的最佳实践是什么

wizardmerlin

2017-12-07 08:48:21 +08:00

`traceback` 推荐.

(默认 python2)

简单写:

```python

import traceback

try:

raise TypeError("Oups!")

except Exception, err:

try:

raise TypeError("Again !?!")

except:

pass

traceback.print_exc()

```

如果要拿到详细信息:

```python

import traceback

import sys

try:

raise TypeError("Oups!")

except Exception, err:

try:

exc_info = sys.exc_info()

# do you usefull stuff here

# (potentially raising an exception)

try:

raise TypeError("Again !?!")

except:

pass

# end of useful stuff

finally:

# Display the *original* exception

traceback.print_exception(*exc_info)

del exc_info

````

输出结果类似如下:

```python

Traceback (most recent call last):

File "t.py", line 6, in

raise TypeError("Oups!")

TypeError: Oups!

```

python3 的话, 输出信息会少一些。

```python

import traceback

try:

raise TypeError("Oups!")

except Exception as err:

try:

raise TypeError("Again !?!")

except:

pass

traceback.print_tb(err.__traceback__)

```

输出大致如下:

```

File "e3.py", line 4, in

raise TypeError("Oups!")

```

关键是还是去看官方文档 traceback 模块:

python2.7: https://docs.python.org/2/library/traceback.html

python3.6: https://docs.python.org/3/library/traceback.html

我的经验来自: [stackoverflow 链接]( https://stackoverflow.com/questions/3702675/how-to-print-the-full-traceback-without-halting-the-program)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值