Python 2.5 won't let me use this syntax:
try:
code_that_raises_exception()
except Exception as e:
print e
raise
So how should I print information about an exception?
Thanks
EDIT: I'm writing a plugin for a program that includes kind of a pseudo python interpreter. It prints print
statements but doesn't show exceptions at all.
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.
Using printStackTrace() method − It print the name of the exception, description and complete stack trace including the line where exception occurred. Using toString() method − It prints the name and description of the exception. Using getMessage() method − Mostly used. It prints the description of the exception.
The try and except block in Python is used to catch and handle exceptions. Python executes code following the try statement as a “normal” part of the program. The code that follows the except statement is the program's response to any exceptions in the preceding try clause.
The most common method to catch and print the exception message in Python is by using except and try statement. You can also save its error message using this method. Another method is to use logger.
the 'as' keyword is a python 3 (introduced in 2.6) addition, you need to use a comma:
try:
code_that_raises_exception()
except Exception, e:
print e
raise
try:
codethatraises()
except Exception, e:
print e
raise
not as easy to read as the latest and greatest syntax, but identical semantics.
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