为什么这行不通?
try:
1/0
except ZeroDivisionError as e:
e.message += ', you fool!'
raise
修改后的消息不会被使用,即使它保留在异常实例上。以上是否有工作模式?行为应该像下面我当前的解决方法:
try:
1/0
except ZeroDivisionError as e:
args = e.args
if not args:
arg0 = ''
else:
arg0 = args[0]
arg0 += ', you fool!'
e.args = (arg0,) + args[1:]
raise
我知道 exception chaining在 python3 中,它看起来不错,但不幸的是在 python2 中不起作用。那么在 python2 中重新引发异常的常用方法是什么?
注意:由于提到的警告和警告 here ,我不想挖掘回溯并创建新的异常,而是重新引发现有异常实例。
最佳答案
更改 e.args
是唯一的方法。 implementation for BaseException.__str__
只考虑 args
元组,它根本不考虑 message
:
static PyObject *
BaseException_str(PyBaseExceptionObject *self)
{
PyObject *out;
switch (PyTuple_GET_SIZE(self->args)) {
case 0:
out = PyString_FromString("");
break;
case 1:
out = PyObject_Str(PyTuple_GET_ITEM(self->args, 0));
break;
default:
out = PyObject_Str(self->args);
break;
}
return out;
}
这应该不会太意外,因为 BaseException.message
is deprecated从 Python 2.6 开始。
关于python - 为什么在异常消息中附加信息不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26488694/