What is the best way to get exceptions' messages from components of standard library in Python?
I noticed that in some cases you can get it via message
field like this:
try:
pass
except Exception as ex:
print(ex.message)
but in some cases (for example, in case of socket errors) you have to do something like this:
try:
pass
except socket.error as ex:
print(ex)
I wondered is there any standard way to cover most of these situations?
This question is related to
python
exception
exception-handling
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
from traceback import format_exc
try:
fault = 10/0
except ZeroDivision:
print(format_exc())
Another possibility is to use the format_exc() method from the traceback module.
I too had the same problem. Digging into this I found that the Exception class has an args
attribute, which captures the arguments that were used to create the exception. If you narrow the exceptions that except will catch to a subset, you should be able to determine how they were constructed, and thus which argument contains the message.
try:
# do something that may raise an AuthException
except AuthException as ex:
if ex.args[0] == "Authentication Timeout.":
# handle timeout
else:
# generic handling
I had the same problem. I think the best solution is to use log.exception, which will automatically print out stack trace and error message, such as:
try:
pass
log.info('Success')
except:
log.exception('Failed')
Source: Stackoverflow.com