Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the proper method of printing Python Exceptions?

        except ImportError as xcpt:
            print "Import Error: " + xcpt.message

Gets you a deprecation warning in 2.6 because message is going away. Stackoverflow

How should you be dealing with ImportError? (Note, this is a built-in exception, not one of my making....)

like image 862
boatcoder Avatar asked Jul 25 '10 21:07

boatcoder


People also ask

How do you print exception 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.

How do I print an exception?

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.

How do I get exception details in Python?

Catching Exceptions in Python In Python, exceptions can be handled using a try statement. The critical operation which can raise an exception is placed inside the try clause. The code that handles the exceptions is written in the except clause.

What are Python exceptions?

An Exception is an error that happens during the execution of a program. Whenever there is an error, Python generates an exception that could be handled. It basically prevents the program from getting crashed.


1 Answers

The correct approach is

xcpt.args

Only the message attribute is going away. The exception will continue to exist and it will continue to have arguments.

Read this: http://www.python.org/dev/peps/pep-0352/ which has some rational for removing the messages attribute.

like image 173
S.Lott Avatar answered Sep 30 '22 13:09

S.Lott