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

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

我们导入 inspect 模块,特别是使用 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

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程

Python 实例