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

📅  最后修改于: 2022-05-13 01:55:31.834000             🧑  作者: Mango

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

在打印错误层次结构之前,让我们了解异常到底是什么?即使我们的代码在语法上是正确的,也会发生异常,但是,在执行时它们会抛出错误。它们不是无条件致命的,我们在执行时遇到的错误称为异常。 Python中有许多内置异常,让我们尝试将它们打印在层次结构中。

为了打印树层次结构,我们将使用Python中的inspect模块。检查模块提供了有用的函数来获取有关对象的信息,例如模块、类、方法、函数和代码对象。例如,它可以帮助您检查类的内容,提取和格式化函数的参数列表。

为了构建树层次结构,我们将使用inspect.getclasstree()。

inspect.getclasstree()将给定的类列表排列成嵌套列表的层次结构。在嵌套列表出现的地方,它包含从其条目紧接在列表之前的类派生的类。

如果唯一参数为真,则给定列表中每个类的返回结构中恰好出现一个条目。否则,使用多重继承的类及其后代将出现多次。

让我们编写一个代码来打印内置异常的树层次结构:

Python3
# import inspect module
import inspect
  
# our treeClass function
def treeClass(cls, ind = 0):
    
      # print name of the class
    print ('-' * ind, cls.__name__)
      
    # iterating through subclasses
    for i in cls.__subclasses__():
        treeClass(i, ind + 3)
  
print("Hierarchy for Built-in exceptions is : ")
  
# inspect.getmro() Return a tuple 
# of class  cls’s base classes.
  
# building a tree hierarchy 
inspect.getclasstree(inspect.getmro(BaseException))
  
# function call
treeClass(BaseException)


输出:

Hierarchy for Built-in exceptions is : 
 BaseException
--- Exception
------ TypeError
------ StopAsyncIteration
------ StopIteration
------ ImportError
--------- ModuleNotFoundError
--------- ZipImportError
------ OSError
--------- ConnectionError
------------ BrokenPipeError
------------ ConnectionAbortedError
------------ ConnectionRefusedError
------------ ConnectionResetError
--------- BlockingIOError
--------- ChildProcessError
--------- FileExistsError
--------- FileNotFoundError
--------- IsADirectoryError
--------- NotADirectoryError
--------- InterruptedError
--------- PermissionError
--------- ProcessLookupError
--------- TimeoutError
--------- UnsupportedOperation
------ EOFError
------ RuntimeError
--------- RecursionError
--------- NotImplementedError
--------- _DeadlockError
------ NameError
--------- UnboundLocalError
------ AttributeError
------ SyntaxError
--------- IndentationError
------------ TabError
------ LookupError
--------- IndexError
--------- KeyError
--------- CodecRegistryError
------ ValueError
--------- UnicodeError
------------ UnicodeEncodeError
------------ UnicodeDecodeError
------------ UnicodeTranslateError
--------- UnsupportedOperation
------ AssertionError
------ ArithmeticError
--------- FloatingPointError
--------- OverflowError
--------- ZeroDivisionError
------ SystemError
--------- CodecRegistryError
------ ReferenceError
------ MemoryError
------ BufferError
------ Warning
--------- UserWarning
--------- DeprecationWarning
--------- PendingDeprecationWarning
--------- SyntaxWarning
--------- RuntimeWarning
--------- FutureWarning
--------- ImportWarning
--------- UnicodeWarning
--------- BytesWarning
--------- ResourceWarning
------ _OptionError
------ error
------ Verbose
------ Error
------ TokenError
------ StopTokenizing
------ EndOfBlock
--- GeneratorExit
--- SystemExit
--- KeyboardInterrupt