如何打印Python异常/错误层次结构?

我们导入检查模块,并专门使用该getclasstree()函数来打印python异常/错误层次结构。

此代码将异常类的给定列表排列并打印到嵌套列表的层次结构中。我们通过一个继承树递归地遍历__subclasses __(),如输出所示。

示例

import inspect
print "The class hierarchy for built-in exceptions is:"
inspect.getclasstree(inspect.getmro(BaseException))
def classtree(cls, indent=0):
print '.' * indent, cls.__name__
for subcls in cls.__subclasses__():
classtree(subcls, indent + 3)
classtree(BaseException)

输出结果

运行代码后,我们得到以下输出。

The class hierarchy for built-in exceptions is:
BaseException
... Exception
...... StandardError
......... TypeError
......... ImportError
............ ZipImportError
......... EnvironmentError
............ IOError
............ OSError
............... WindowsError
......... EOFError
......... RuntimeError
............ NotImplementedError
......... NameError
............ UnboundLocalError
......... AttributeError
......... SyntaxError
............ IndentationError
............... TabError
......... LookupError
............ IndexError
............ KeyError
............ CodecRegistryError
......... ValueError
............ UnicodeError
............... UnicodeEncodeError
............... UnicodeDecodeError
............... UnicodeTranslateError
......... AssertionError
......... ArithmeticError
............ FloatingPointError
............ OverflowError
............ ZeroDivisionError
......... SystemError
............ CodecRegistryError
......... ReferenceError
......... MemoryError
......... BufferError
...... StopIteration
...... Warning
......... UserWarning
......... DeprecationWarning
......... PendingDeprecationWarning
......... SyntaxWarning
......... RuntimeWarning
......... FutureWarning
......... ImportWarning
......... UnicodeWarning
......... BytesWarning
...... _OptionError
...... error
...... Error
...... TokenError
...... StopTokenizing
...... error
...... EndOfBlock
... GeneratorExit
... SystemExit
... KeyboardInterrupt