boatcoder
boatcoder

Reputation: 18117

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....)

Upvotes: 9

Views: 7048

Answers (2)

Ned Batchelder
Ned Batchelder

Reputation: 375892

If you want to print the exception:

print "Couldn't import foo.bar.baz: %s" % xcpt

Exceptions have a __str__ method defined to create a readable version of themselves. I wouldn't bother with "Import Error:" since the exception will provide that itself. If you add text to the exception, make it be something you know based on the code you were trying to execute.

Upvotes: 2

S.Lott
S.Lott

Reputation: 391972

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.

Upvotes: 9

Related Questions