【发布时间】:2018-12-11 04:26:59
【问题描述】:
我在 Python 3 中有一个脚本,它使用“from”关键字重新引发异常(如对 Stackoverflow 问题的回答所示:Re-raise exception with a different type and message, preserving existing information)
我现在必须回去使脚本与 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 中重新引发适用于 Python 2.7 和 Python 3 的异常?
【问题讨论】:
标签: python python-3.x python-2.7