gpt4 book ai didi

python - 为什么 except object 不能捕获 Python 中的所有内容?

转载 作者:太空狗 更新时间:2023-10-29 17:20:41 26 4
gpt4 key购买 nike

section 7.4 中的 python 语言引用说明:

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'

最佳答案

我相信可以在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 block 中使用无效的异常类型将显示警告。

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

Tadhgs-MacBook-Pro:~ Tadhg$ python2 -3 /Users/Tadhg/Documents/codes/test.py
True
/Users/Tadhg/Documents/codes/test.py:5: DeprecationWarning: catching classes that don't inherit from BaseException is not allowed in 3.x
except object:
Traceback (most recent call last):
File "/Users/Tadhg/Documents/codes/test.py", line 4, in <module>
raise AssertionError()
AssertionError

关于python - 为什么 except object 不能捕获 Python 中的所有内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38751530/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com