在 Python 中获取异常值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4308182/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 15:12:10  来源:igfitidea点击:

Getting the exception value in Python

pythonexception

提问by Frias

If I have that code:

如果我有那个代码:

try:
    some_method()
except Exception, e:

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

我怎样才能得到这个异常值(我的意思是字符串表示)?

采纳答案by aaronasterling

use str

str

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

Also, most exception classes will have an argsattribute. Often, args[0]will be an error message.

此外,大多数异常类都有一个args属性。通常,args[0]会出现错误信息。

It should be noted that just using strwill return an empty string if there's no error message whereas using repras 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.

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

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?

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

回答by pyfunc

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

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

Using repr:

使用repr

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

Using str:

使用str

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

回答by cedbeu

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.

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

str(e)might return the string with surrounding quotes and possibly with the leading uif unicode:

str(e)可能会返回带有周围引号的字符串,并且可能带有前导uif unicode:

'integer division or modulo by zero'

repr(e)gives the full exception representation which is not probably what you want:

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

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

edit

编辑

My bad !!! It seems that BaseException.messagehas 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.argsand str(e)depending on your needs (and possibly e.messageif the lib you are using is relying on that mechanism).

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

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

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

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

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

回答by Blckknght

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

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

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.

用于traceback.print_exc()将当前异常打印到标准错误,就像如果它没有被捕获就会被打印,或者traceback.format_exc()获得与字符串相同的输出。如果您想限制输出或将打印重定向到类似文件的对象,您可以将各种参数传递给这些函数中的任何一个。

回答by apporc

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

对于python2,最好使用e.message获取异常信息,这样可以避免可能的UnicodeDecodeError. 但是e.message对于某些类型的异常OSError,yes将为空,在这种情况下,我们可以将 a 添加exc_info=True到我们的日志记录函数中,以免错过错误。
对于 python3,我认为使用str(e).

回答by Kostanos

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:

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

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

回答by DanGoodrick

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

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

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