Python Exception与BaseException

Python Exception与BaseException

Python 的所有的错误都是从 BaseException 类 继承 而来的。BaseException 类包含了所有的异常与错误类型,包含了 built-in exceptions。

Exception 类不包含所有的 built-in exceptions,只包含 built-in, non-system-exiting exceptions,像 SystemExit 类型的 exception 就不包含在里面。

因此作为子类的 Exception 无法截获父类 BaseException 类型的错误。

Python异常类继承关系

BaseException +-- SystemExit +-- KeyboardInterrupt +-- GeneratorExit +-- Exception +-- StopIteration +-- StopAsyncIteration +-- ArithmeticError | +-- FloatingPointError | +-- OverflowError | +-- ZeroDivisionError +-- AssertionError +-- AttributeError +-- BufferError +-- EOFError +-- ImportError | +-- ModuleNotFoundError +-- LookupError | +-- IndexError | +-- KeyError +-- MemoryError +-- NameError | +-- UnboundLocalError +-- OSError | +-- BlockingIOError | +-- ChildProcessError | +-- ConnectionError | | +-- BrokenPipeError | | +-- ConnectionAbortedError | | +-- ConnectionRefusedError | | +-- ConnectionResetError | +-- FileExistsError | +-- FileNotFoundError | +-- InterruptedError | +-- IsADirectoryError | +-- NotADirectoryError | +-- PermissionError | +-- ProcessLookupError | +-- TimeoutError +-- ReferenceError +-- RuntimeError | +-- NotImplementedError | +-- RecursionError +-- SyntaxError | +-- IndentationError | +-- TabError +-- SystemError +-- TypeError +-- ValueError | +-- UnicodeError | +-- UnicodeDecodeError | +-- UnicodeEncodeError | +-- UnicodeTranslateError +-- Warning +-- DeprecationWarning +-- PendingDeprecationWarning +-- RuntimeWarning +-- SyntaxWarning +-- UserWarning +-- FutureWarning +-- ImportWarning +-- UnicodeWarning +-- BytesWarning +-- ResourceWarning

从以上继承关系,我们可以看出,BaseException 是 Exception 的父类,BaseException 比 Exception 多了三个类型的异常,即: SystemExit、KeyboardInterrupt 与 GeneratorExit。

Python Exception与BaseException总结

Python 的所有的错误都是从 BaseException 类继承而来的。BaseException 类包含了所有的异常与错误类型,包含了 built-in exceptions。Exception 类不包含所有的 built-in exceptions,只包含 built-in, non-system-exiting exceptions。