The best answers to the question “Getting the exception value in Python” in the category Dev.
If I have that code:
try: some_method() except Exception, e:
How can I get this Exception value (string
representation I mean)?
Use repr() and The difference between using repr and str
>>> try: ... print(x) ... except Exception as e: ... print(repr(e)) ... NameError("name 'x' is not defined")
>>> try: ... print(x) ... except Exception as e: ... print(str(e)) ... name 'x' is not defined
try: some_method() except Exception as e: s = str(e)
Also, most exception classes will have an
args attribute. Often,
args will be an error message.
It should be noted that just using
str will return an empty string if there’s no error message whereas using
repr as pyfunc recommends will at least display the class of the exception. My take is that if you’re printing it out, it’s for an end user that doesn’t care what the class is and just wants an error message.
It really depends on the class of exception that you are dealing with and how it is instantiated. Did you have something in particular in mind?
Another way hasn’t been given yet:
try: 1/0 except Exception, e: print e.message
integer division or modulo by zero
args might actually not be a message.
str(e) might return the string with surrounding quotes and possibly with the leading
u if unicode:
'integer division or modulo by zero'
repr(e) gives the full exception representation which is not probably what you want:
"ZeroDivisionError('integer division or modulo by zero',)"
My bad !!! It seems that
BaseException.message has been deprecated from
2.6, finally, it definitely seems that there is still not a standardized way to display exception messages. So I guess the best is to do deal with
str(e) depending on your needs (and possibly
e.message if the lib you are using is relying on that mechanism).
For instance, with
e.message is the only way to display correctly the exception, using
str(e) will surround the message with
MySQLdb, the proper way to retrieve the message is
e.message is empty, and
str(e) will display
Even though I realise this is an old question, I’d like to suggest using the
traceback module to handle output of the exceptions.
traceback.print_exc() to print the current exception to standard error, just like it would be printed if it remained uncaught, or
traceback.format_exc() to get the same output as a string. You can pass various arguments to either of those functions if you want to limit the output, or redirect the printing to a file-like object.