【问题标题】:Re-raising exception, in a way agnostic to Python 2 and Python 3 [duplicate]以与 Python 2 和 Python 3 无关的方式重新引发异常 [重复]
【发布时间】: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


    【解决方案1】:
    # 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)
    

    【讨论】:

    • 太棒了,这在 python3 中有效,谢谢!
    • @ffConundrums 不用担心!查看this。这是编写 2 和 3 兼容代码的绝佳资源!
    • 这是救命稻草 - 谢谢!!
    猜你喜欢
    • 1970-01-01
    • 2014-06-25
    • 2011-09-12
    • 2021-10-04
    • 1970-01-01
    • 1970-01-01
    • 2023-03-31
    • 1970-01-01
    • 2018-11-13
    相关资源
    最近更新 更多