To improve on the answer provided by @artofwarfare, here is what I consider a neater way to check for the message
attribute and print it or print the Exception
object as a fallback.
try:
pass
except Exception as e:
print getattr(e, 'message', repr(e))
The call to repr
is optional, but I find it necessary in some use cases.
Update #1:
Following the comment by @MadPhysicist, here's a proof of why the call to repr
might be necessary. Try running the following code in your interpreter:
try:
raise Exception
except Exception as e:
print(getattr(e, 'message', repr(e)))
print(getattr(e, 'message', str(e)))
Update #2:
Here is a demo with specifics for Python 2.7 and 3.5: https://gist.github.com/takwas/3b7a6edddef783f2abddffda1439f533