python - 为什么在异常消息中附加信息不起作用?

标签 python exception

为什么这行不通?

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/

相关文章:

python - 不能 "activate"virtualenv

python - 如何将函数应用于元素集合

python - keras predict_generator 在使用 keras.utils.Sequence 时正在改组其输出

javascript - 自定义异常类型

javascript - 我怎样才能包装这些函数以便它们的异常总是得到处理?

python - 在 Google App Engine 中获取 TypeError

python - 列表输出中需要 float

android - 改造 |句柄 "server not found exception"

java - 捕获 Hibernate/JPA/Session 唯一键重复异常的最佳实践

java - 哪些异常会杀死 Java 中的 Web 应用程序