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
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.
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.
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.
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.
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...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With