尝试...除了...作为Python 2.5中的错误 - Python 3.x

时间:2022-04-03 02:33:37

I want to keep & use the error value of an exception in both Python 2.5, 2.7 and 3.2.

我想在Python 2.5,2.7和3.2中保留并使用异常的错误值。

In Python 2.5 and 2.7 (but not 3.x), this works:

在Python 2.5和2.7(但不是3.x)中,这适用于:

try:
    print(10 * (1/0))
except ZeroDivisionError,  error:       # old skool
    print("Yep, error caught:", error)

In Python 2.7 and 3.2 (but not in 2.5), this works:

在Python 2.7和3.2中(但不在2.5中),这适用于:

try:
    print(10 * (1/0))
except (ZeroDivisionError) as error:    # 'as' is needed by Python 3
    print("Yep, error caught:", error)

Is there any code for this purpose that works in both 2.5, 2.7 and 3.2?

是否有任何代码可用于2.5,2.7和3.2?

Thanks

1 个解决方案

#1


38  

You can use one code base on Pythons 2.5 through 3.2, but it isn't easy. You can take a look at coverage.py, which runs on 2.3 through 3.3 with a single code base.

你可以在Pythons 2.5到3.2上使用一个代码库,但这并不容易。你可以看看coverage.py,它运行在2.3到3.3之间,只有一个代码库。

The way to catch an exception and get a reference to the exception that works in all of them is this:

捕获异常并获取对所有异常都有效的异常的方法是这样的:

except ValueError:
    _, err, _ = sys.exc_info()
    #.. use err...

This is equivalent to:

这相当于:

except ValueError as err:
    #.. use err...

#1


38  

You can use one code base on Pythons 2.5 through 3.2, but it isn't easy. You can take a look at coverage.py, which runs on 2.3 through 3.3 with a single code base.

你可以在Pythons 2.5到3.2上使用一个代码库,但这并不容易。你可以看看coverage.py,它运行在2.3到3.3之间,只有一个代码库。

The way to catch an exception and get a reference to the exception that works in all of them is this:

捕获异常并获取对所有异常都有效的异常的方法是这样的:

except ValueError:
    _, err, _ = sys.exc_info()
    #.. use err...

This is equivalent to:

这相当于:

except ValueError as err:
    #.. use err...