Reputation: 943
I want to keep & use the error value of an exception in both Python 2.5, 2.7 and 3.2.
In Python 2.5 and 2.7 (but not 3.x), this works:
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:
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?
Thanks
Upvotes: 32
Views: 27903
Reputation: 375484
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.
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...
Upvotes: 41