Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the exception value in Python

If I have that code:

try:
    some_method()
except Exception, e:

How can I get this Exception value (string representation I mean)?

like image 658
Frias Avatar asked Nov 29 '10 21:11

Frias


People also ask

Can we return value in exception in Python?

You can't "raise" and "return" in the same time, so you have to add a special variable to the return value (e.g: in tuple) in case of error. E.g: I have a function (named "func") which counts something and I need the (partial) result even if an exception happened during the counting.


6 Answers

use str

try:
    some_method()
except Exception as e:
    s = str(e)

Also, most exception classes will have an args attribute. Often, args[0] 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?

like image 197
aaronasterling Avatar answered Oct 17 '22 17:10

aaronasterling


Use repr() and The difference between using repr and str

Using repr:

>>> try:
...     print(x)
... except Exception as e:
...     print(repr(e))
... 
NameError("name 'x' is not defined")

Using str:

>>> try:
...     print(x)
... except Exception as e:
...     print(str(e))
... 
name 'x' is not defined
like image 32
pyfunc Avatar answered Oct 17 '22 18:10

pyfunc


Even though I realise this is an old question, I'd like to suggest using the traceback module to handle output of the exceptions.

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

like image 28
Blckknght Avatar answered Oct 17 '22 17:10

Blckknght


Another way hasn't been given yet:

try:
    1/0
except Exception, e:
    print e.message

Output:

integer division or modulo by zero

args[0] 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',)"

edit

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 e.args and str(e) depending on your needs (and possibly e.message if the lib you are using is relying on that mechanism).

For instance, with pygraphviz, e.message is the only way to display correctly the exception, using str(e) will surround the message with u''.

But with MySQLdb, the proper way to retrieve the message is e.args[1]: e.message is empty, and str(e) will display '(ERR_CODE, "ERR_MSG")'

like image 39
cedbeu Avatar answered Oct 17 '22 16:10

cedbeu


To inspect the error message and do something with it (with Python 3)...

try:
    some_method()
except Exception as e:
    if {value} in e.args:
        {do something}
like image 44
DanGoodrick Avatar answered Oct 17 '22 17:10

DanGoodrick


For python2, It's better to use e.message to get the exception message, this will avoid possible UnicodeDecodeError. But yes e.message will be empty for some kind of exceptions like OSError, in which case we can add a exc_info=True to our logging function to not miss the error.
For python3, I think it's safe to use str(e).

like image 36
apporc Avatar answered Oct 17 '22 17:10

apporc