首页 > 如何在Python2下使用异常链并保留traceback?

如何在Python2下使用异常链并保留traceback?

参考Cheat Sheet: Writing Python 2-3 compatible code所说,如下代码可以在python2上使用异常链:

# py6.py
import sys
import traceback
from future.utils import raise_from, raise_with_traceback

def outer():
    try:
        inner()
    except ValueError as ex:
        raise_from(RuntimeError('RuntimeError with tb'), ex)

def inner():
    raise_with_traceback(ValueError("dodgy value"))

try:
    outer()
except RuntimeError as e:
    traceback.print_exc()

可是,输出的信息如下:

Traceback (most recent call last):
  File "py6.py", line 16, in <module>
    outer()
  File "py6.py", line 10, in outer
    raise_from(RuntimeError('RuntimeError with tb'), ex)
  File ".../lib/python2.7/site-packages/future/utils/__init__.py", line 438, in raise_from
    raise e
RuntimeError: RuntimeError with tb

最后捕获到的RuntimeError虽然包括了之前的ValueError(在__cause__中),但是却丢失了traceback信息。(不像Py3,Py2没有__tracebakc__属性)

如何才能同时使用异常链和traceback信息呢?希望不需要大改代码,比如把所有的except块改写一遍就太麻烦了。


另外,如下代码可以输出traceback信息,但是却没有异常链了。

import sys
import traceback
from future.utils import raise_with_traceback

def outer():
    try:
        inner()
    except ValueError as e:
        raise_with_traceback(RuntimeError('RuntimeError with tb'))

def inner():
    raise_with_traceback(ValueError('ValueError'))

try:
    outer()
except Exception as e:
    traceback.print_exc()
【热门文章】
【热门文章】