在Python中获取异常值

问题:在Python中获取异常值

如果我有该代码:

try:
    some_method()
except Exception, e:

我如何获得此Exception值(我的意思是字符串表示)?

If I have that code:

try:
    some_method()
except Exception, e:

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


回答 0

str

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

同样,大多数异常类都具有args属性。通常,args[0]将是错误消息。

应该注意的是,str如果没有错误消息,仅使用将返回一个空字符串,而使用reprpyfunc建议使用至少将显示异常的类。我的看法是,如果要打印出来,它是针对最终用户的,它并不关心类是什么,只需要一条错误消息。

它实际上取决于您要处理的异常类以及如何实例化它。您有什么特别的想法吗?

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?


回答 1

使用repr()和使用repr和str之间的区别

使用repr

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

使用str

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

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

回答 2

即使我意识到这是一个老问题,我还是建议使用traceback模块来处理异常的输出。

用于traceback.print_exc()将当前异常打印为标准错误,就像在未捕获的情况下将其打印一样,或者traceback.format_exc()将其作为字符串输出。如果要限制输出,或者可以将打印重定向到类似文件的对象,则可以将各种参数传递给这些函数中的任何一个。

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.


回答 3

尚未给出另一种方式:

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

输出:

integer division or modulo by zero

args[0] 可能实际上不是消息。

str(e)可能返回带引号的字符串,u如果可能,则返回带前导的字符串:

'integer division or modulo by zero'

repr(e) 给出完整的异常表示,这可能不是您想要的:

"ZeroDivisionError('integer division or modulo by zero',)"

编辑

我的错 !!!似乎BaseException.message 已从弃用2.6,最后,似乎仍然没有标准化的方式来显示异常消息。所以我想最好是做处理e.argsstr(e)根据您的需要(也可能是e.message,如果你正在使用的lib是依靠这一机制)。

例如,使用pygraphvize.message是正确显示异常的唯一方法,使用str(e)将消息包围u''

但是,使用MySQLdb,检索消息的正确方法是e.args[1]e.message为空,str(e)并将显示'(ERR_CODE, "ERR_MSG")'

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")'


回答 4

对于python2,最好使用e.message来获取异常消息,这样可以避免可能UnicodeDecodeError。但是yes e.message对于某些异常(如)将为空OSError,在这种情况下,我们可以exc_info=True向日志记录功能中添加a ,以免出错。
对于python3,我认为使用是安全的str(e)

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


回答 5

如果您不知道错误的类型/来源,可以尝试:

import sys
try:
    doSomethingWrongHere()
except:
    print('Error: {}'.format(sys.exc_info()[0]))

但是请注意,您会收到pep8警告:

[W] PEP 8 (E722): do not use bare except

If you don’t know the type/origin of the error, you can try:

import sys
try:
    doSomethingWrongHere()
except:
    print('Error: {}'.format(sys.exc_info()[0]))

But be aware, you’ll get pep8 warning:

[W] PEP 8 (E722): do not use bare except

回答 6

要检查错误消息并对其进行处理(使用Python 3)…

try:
    some_method()
except Exception as e:
    if {value} in e.args:
        {do something}

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}