重新引发异常,在某种程度上与 Python 2 和 Python 3 无关



我在Python 3中有一个脚本,它使用"from"关键字重新引发异常(如这个Stackoverflow问题的答案所示:使用不同的类型和消息重新引发异常,保留现有信息(

我现在必须回去使脚本与 Python 2.7 兼容。 在 Python 2.7 中,"from"关键字不能以这种方式使用。 我发现在 Python 2 中,重新引发异常的方法如下:

try:
foo()
except ZeroDivisionError as e:
import sys
raise MyCustomException, MyCustomException(e), sys.exc_info()[2]

但是,虽然此语法适用于 Python 2.7,但不适用于 Python 3。

有没有一种可接受的方法来重新引发适用于Python 2.7和Python 3的Python中的异常?

# Python 3 only
try:
frobnicate()
except KeyError as exc:
raise ValueError("Bad grape") from exc
# Python 2 and 3:
from future.utils import raise_from
try:
frobnicate()
except KeyError as exc:
raise_from(ValueError("Bad grape"), exc)

最新更新