3年前我写了一篇文章 python classic, static, class and abstract methods ,现在似乎到了更新的时候,今天我想来剖析和讨论 Python 异常。
剖析异常基础类
Python 异常的基础类名为 BaseException。这个类在程序和库中很少用,更多时候它被当成是异常的实现细节。为了了解异常是怎么实现的,我们可以阅读 CPython 源码中的 Objects/exceptions.c 文件。在这个文件中你可以看到 BaseException 类中定义的所有基础方法和异常的属性。而我们常用的 Exception 类则继承于 BaseException,该类只包含如下代码:
/** Exception extends BaseException
*/
SimpleExtendsException(PyExc_BaseException, Exception,
"Common base class for all non-exit exceptions.");
另外一些直接继承 BaseException 的类是 GeneratorExit、 SystemExit 和 KeyboardInterrupt。而其他内置的异常一般直接从 Exception 类中继承。你可以通过 pydoc2 exceptions 或者 pydoc3 builtins 命令来查看整个异常的结构。
这里是在 Python 2 和 3 中通过这个 脚本 生成的内置异常继承结构图。