Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

try ... except ... as error in Python 2.5 - Python 3.x

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

like image 383
superkoning Avatar asked Jul 01 '12 20:07

superkoning


People also ask

How do you use try and except in Python 3?

The try block lets you test a block of code for errors. The except block lets you handle the error. The else block lets you execute code when there is no error. The finally block lets you execute code, regardless of the result of the try- and except blocks.

How do you raise in Python 3?

Python raise Keyword is used to raise exceptions or errors. The raise keyword raises an error and stops the control flow of the program. It is used to bring up the current exception in an exception handler so that it can be handled further up the call stack.

What can I use instead of try and except in Python?

Moreover, if your input is allowed to contain extra spaces, you can use something like splitted[2]. strip() . Readings on SO/SE about the try-except matter.

How do I print error try except in Python?

If you are going to print the exception, it is better to use print(repr(e)) ; the base Exception. __str__ implementation only returns the exception message, not the type. Or, use the traceback module, which has methods for printing the current exception, formatted, or the full traceback.


1 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... 
like image 104
Ned Batchelder Avatar answered Sep 28 '22 12:09

Ned Batchelder