Python 中是否有 Exception 超类,例如 Java Exception 的 Throwable?

Aks*_*rma 2 python exception hierarchy

ExceptionPython中的超类是什么?请向我提供 Python 异常层次结构。

jfs*_*jfs 6

Exception的基类:

>>> Exception.__bases__
(BaseException,)
Run Code Online (Sandbox Code Playgroud)

文档中的异常层次结构确认它是所有异常的基类:

BaseException
 +-- SystemExit
 +-- KeyboardInterrupt
 +-- GeneratorExit
 +-- Exception
      +-- StopIteration
      +-- ArithmeticError
      |    +-- FloatingPointError
...
Run Code Online (Sandbox Code Playgroud)

捕获所有异常的语法是:

try:
    raise anything
except: 
    pass
Run Code Online (Sandbox Code Playgroud)

注意:非常非常谨慎地使用它,例如,__del__当世界可能被一半摧毁并且没有其他选择时,您可以在清理期间的方法中使用它。

Python 2 允许引发并非源自以下的异常BaseException

>>> raise 1
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: exceptions must be old-style classes or derived from BaseException, not int
>>> class A: pass
... 
>>> raise A
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
__main__.A: <__main__.A instance at 0x7f66756faa28>
Run Code Online (Sandbox Code Playgroud)

它在 Python 3 中得到修复,强制执行该规则:

>>> raise 1
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: exceptions must derive from BaseException
Run Code Online (Sandbox Code Playgroud)


shx*_*hx2 5

您正在寻找BaseException.

用户定义的异常类型应该子类化Exception

请参阅文档