Fri*_*ias 222 python exception
如果我有那个代码:
try:
some_method()
except Exception, e:
Run Code Online (Sandbox Code Playgroud)
如何获得此Exception值(我的意思是字符串表示)?
谢谢
aar*_*ing 302
使用 str
try:
some_method()
except Exception as e:
s = str(e)
Run Code Online (Sandbox Code Playgroud)
此外,大多数异常类都有一个args
属性.通常,这args[0]
将是一条错误消息.
应该注意的是,str
如果没有错误消息,只使用将返回空字符串,而使用repr
pyfunc建议将至少显示异常的类.我的看法是,如果你打印出来的话,最终用户并不关心这个类是什么,只是想要一个错误信息.
它实际上取决于您正在处理的异常类以及它是如何实例化的.你有什么特别的想法吗?
pyf*_*unc 164
使用repr()和使用repr和str之间的区别
使用repr:
>>> try:
... print(x)
... except Exception as e:
... print(repr(e))
...
NameError("name 'x' is not defined")
Run Code Online (Sandbox Code Playgroud)
使用str:
>>> try:
... print(x)
... except Exception as e:
... print(str(e))
...
name 'x' is not defined
Run Code Online (Sandbox Code Playgroud)
Blc*_*ght 25
即使我意识到这是一个老问题,我还是建议使用该traceback
模块来处理异常的输出.
用于traceback.print_exc()
将当前异常打印到标准错误,就像它在未被捕获时打印一样,或者traceback.format_exc()
获得与字符串相同的输出.如果要限制输出,可以将各种参数传递给其中任何一个函数,或者将打印重定向到类文件对象.
ced*_*beu 22
另一种方式还没有给出:
try:
1/0
except Exception, e:
print e.message
Run Code Online (Sandbox Code Playgroud)
输出:
integer division or modulo by zero
Run Code Online (Sandbox Code Playgroud)
args[0]
实际上可能不是一条消息.
str(e)
可能会返回带有周围引号的字符串,并且可能返回带有前导u
if的unicode:
'integer division or modulo by zero'
Run Code Online (Sandbox Code Playgroud)
repr(e)
给出完整的异常表示,这可能不是你想要的:
"ZeroDivisionError('integer division or modulo by zero',)"
Run Code Online (Sandbox Code Playgroud)
编辑
我的错 !!!它似乎BaseException.message
已被弃用2.6
,最后,似乎仍然没有标准化的方式来显示异常消息.所以我想最好是做处理e.args
,并str(e)
根据您的需要(也可能是e.message
,如果你正在使用的lib是依靠这一机制).
例如,使用pygraphviz
,e.message
是唯一正确显示异常的方法,使用str(e)
将围绕消息u''
.
但是MySQLdb
,检索消息的正确方法是e.args[1]
:e.message
为空,str(e)
并将显示'(ERR_CODE, "ERR_MSG")'
以下对我有用:
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())
Run Code Online (Sandbox Code Playgroud)
如果some_method()
引发异常ValueError("asdf")
,则会打印您在回溯中看到的内容 - 减去回溯:ValueError: asdf
。
要检查错误消息并对其执行某些操作(使用 Python 3)...
try:
some_method()
except Exception as e:
if {value} in e.args:
{do something}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
219837 次 |
最近记录: |