【问题标题】:Why is it recommended to derive from Exception instead of BaseException class in Python?为什么建议从 Python 中的 Exception 而不是 BaseException 类派生?
【发布时间】:2015-01-17 01:01:14
【问题描述】:

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

我很好奇为什么推荐这种方式?是否只是为了保留 Python 开发人员所设想的 exceptions hierarchy

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

【问题讨论】:

标签: python exception


【解决方案1】:

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 解释原因。

现在异常层次结构变得更加重要,因为它有一个 基本根,需要对现有层次结构进行更改。作为它 现在,如果要捕获所有表示错误的异常 并不意味着应该允许口译员退出,您必须 在 except 子句中明确指定除两个例外之外的所有例外,或 分别捕获两个异常,然后重新引发它们并拥有 所有其他例外都属于一个空的 except 子句:

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

这是不必要的明确。该 PEP 建议移动 KeyboardInterrupt 和 SystemExit 直接继承自 基本异常。

【讨论】:

    猜你喜欢
    • 2017-03-30
    • 2012-07-14
    • 1970-01-01
    • 2013-07-22
    • 1970-01-01
    • 2018-11-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多