如果我有这个代码:

try:
    some_method()
except Exception, e:

我怎么能得到这个异常值(字符串 我是说代表)?


当前回答

下面的方法对我很有效:

import traceback

try:
    some_method()
except Exception as e:
   # Python 3.9 or older
   print("".join(traceback.format_exception_only(type(e), e)).strip())
   # Python 3.10+
   print("".join(traceback.format_exception_only(e)).strip())

如果some_method()引发异常ValueError("asdf"),将打印您在回溯中看到的内容——减去traceback: ValueError: asdf。

这里是关于这个的文档。

其他回答

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

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

对于python2,最好使用e.message来获取异常消息,这将避免可能的UnicodeDecodeError。但是,对于OSError之类的某些异常,e.message将为空,在这种情况下,我们可以在日志函数中添加一个exc_info=True,以避免错过错误。 对于python3,我认为使用str(e)是安全的。

使用str

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

而且,大多数异常类都有一个args属性。通常,args[0]将是一个错误消息。

值得注意的是,如果没有错误消息,仅使用str将返回一个空字符串,而按照pyfunc建议使用repr将至少显示异常的类。我的看法是,如果您要打印它,那么它是为终端用户准备的,他们并不关心类是什么,只是想要一个错误消息。

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

使用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

另一种方法还没有给出:

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

输出:

integer division or modulo by zero

Args[0]可能不是消息。

如果unicode, Str (e)可能会返回带引号的字符串,并且可能带有前导u:

'integer division or modulo by zero'

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

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

edit

我的错!!似乎BaseException。Message从2.6开始就已经弃用了,最后,似乎仍然没有一个标准化的方式来显示异常消息。所以我想最好的方法是根据你的需要处理e.args和str(e)(如果你使用的库依赖于这种机制,可能还有e.message)。

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

但是在MySQLdb中,获取消息的正确方法是e.args[1]: e.message是空的,str(e)将显示'(ERR_CODE, "ERR_MSG")'