gpt4 book ai didi

python - 以与 Python 2 和 Python 3 无关的方式重新引发异常

转载 作者:行者123 更新时间:2023-12-01 01:47:20 24 4
gpt4 key购买 nike

我有一个 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 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)

关于python - 以与 Python 2 和 Python 3 无关的方式重新引发异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51144708/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com