try … except … as error in Python 2.5 – Python 3.x

Question:

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

Asked By: superkoning

||

Answers:

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...
Answered By: Ned Batchelder
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.