为什么我们不应该扩展BaseException类?

2024-04-20 02:24:21 发布

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

为什么我们不应该扩展BaseException类来创建我们自己的异常,而不是扩展Python2.7中的异常类?你知道吗


Tags: baseexception
1条回答
网友
1楼 · 发布于 2024-04-20 02:24:21

让我们看看Exception hierarchy。你知道吗

BaseException派生的唯一例外是SystemExitKeyboardInterruptGeneratorExit。他们是例外,不应该被意外抓住。这就是他们与众不同的原因。你知道吗

引用^{}

The exception inherits from BaseException so as to not be accidentally caught by code that catches Exception and thus prevent the interpreter from exiting.

这也是不应该在没有指定异常类型的情况下使用try: ... except: ...的原因。你知道吗

相关问题 更多 >