为什么除了object不能捕获Python中的所有内容?

2024-05-17 18:29:40 发布

您现在位置:Python中文网/ 问答频道 /正文

python语言引用以section 7.4表示:

For an except clause with an expression, that expression is evaluated, and the clause matches the exception if the resulting object is “compatible” with the exception. An object is compatible with an exception if it is the class or a base class of the exception object, or a tuple containing an item compatible with the exception.

那么,为什么except object:不能捕获所有内容?object是所有异常类的基类,因此except object:应该能够捕获每个异常。在

例如,这应该捕捉AssertionError

print isinstance(AssertionError(), object) # prints True
try:
    raise AssertionError()
except object:
    # This block should execute but it never does.
    print 'Caught exception'

Tags: ortheanifobjectiswithexception
1条回答
网友
1楼 · 发布于 2024-05-17 18:29:40

我相信答案可以在source code for python 2.7中找到:

        else if (Py_Py3kWarningFlag  &&
                 !PyTuple_Check(w) &&
                 !Py3kExceptionClass_Check(w))
        {
            int ret_val;
            ret_val = PyErr_WarnEx(
                PyExc_DeprecationWarning,
                CANNOT_CATCH_MSG, 1);
            if (ret_val < 0)
                return NULL;
        }

因此,如果w(我假设except语句中的表达式)不是元组或异常类,并且设置了Py_Py3kWarningFlag,那么尝试在except块中使用无效的异常类型将显示警告。在

该标志是通过在执行文件时添加-3标志来设置的:

^{pr2}$

相关问题 更多 >