在Python 2中传播异常,保留了回溯

时间:2014-07-10 12:08:42

标签: python exception

我有一个Python代码,我希望捕获所有可能的异常并提升我自己的自定义异常,但保留尽可能多的信息。

在Python 3中,有一个构造raise from或多或少地做了我想要的

def function():
    return 1 / 0

class MyException(Exception):
    pass

try:
    function()
except Exception as err:
    raise MyException(err) from err

输出

Traceback (most recent call last):
  File "capture.py", line 9, in <module>
   function()
  File "capture.py", line 3, in function
    return 1 / 0
ZeroDivisionError: division by zero

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "capture.py", line 11, in <module>
    raise MyException(err) from err
__main__.MyException: division by zero

有没有办法在Python 2中获得类似的结果?

因此,为了将来参考,答案是肯定的。 鉴于链接问题的答案,我可以通过以下代码实现我想要的东西

import sys

def function():
    return 1 / 0

class MyException(Exception):
    pass

try:
    function()
except Exception as err:
    raise MyException, err, sys.exc_info()[2]

0 个答案:

没有答案