gpt4 book ai didi

python - 为什么建议从 Exception 派生而不是 Python 中的 BaseException 类?

转载 作者:太空狗 更新时间:2023-10-29 20:51:47 25 4
gpt4 key购买 nike

Python 2 documentation说“鼓励程序员从 Exception 类或其子类之一派生新的异常,而不是从 BaseException”。没有进一步解释原因。

我很好奇为什么会这样推荐?是否只是为了保留 exceptions hierarchy正如 Python 开发人员所设想的那样?

>>> dir(BaseException) == dir(Exception)
True

最佳答案

BaseException 派生的异常是:GeneratorExitKeyboardInterruptSystemExit

根据文档:

  • GeneratorExit :调用生成器的 close() 方法时引发。它直接继承自 BaseException 而不是 StandardError,因为它在技术上不是错误。
  • KeyboardInterrupt :当用户按下中断键(通常是 Control-C 或 Delete)时引发。在执行期间,定期检查中断。当内置函数 input() 或 raw_input() 等待输入时键入的中断也会引发此异常。 异常继承自BaseException,以免被捕获Exception的代码意外捕获,从而阻止解释器退出。
  • SystemExit :异常继承自BaseException,而不是StandardError或Exception,这样就不会被捕获Exception的代码意外捕获。 这允许异常正确向上传播并导致解释器退出。

所以通常的原因是防止try ... except Exception不小心阻止解释器退出(除了GeneratorExit)

在看到 Ashwini Chaudhary 的评论后

更新:

PEP 352 - Required Superclass for Exceptions解释原因。

With the exception hierarchy now even more important since it has a basic root, a change to the existing hierarchy is called for. As it stands now, if one wants to catch all exceptions that signal an error and do not mean the interpreter should be allowed to exit, you must specify all but two exceptions specifically in an except clause or catch the two exceptions separately and then re-raise them and have all other exceptions fall through to a bare except clause:

except (KeyboardInterrupt, SystemExit):
raise
except:
...

That is needlessly explicit. This PEP proposes moving KeyboardInterrupt and SystemExit to inherit directly from BaseException.

关于python - 为什么建议从 Exception 派生而不是 Python 中的 BaseException 类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27995057/

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