如果我有这个代码:

try:
    some_method()
except Exception, e:

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


当前回答

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

其他回答

对于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将至少显示异常的类。我的看法是,如果您要打印它,那么它是为终端用户准备的,他们并不关心类是什么,只是想要一个错误消息。

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

下面的方法对我很有效:

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}

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