如何编写打印 Python 异常/错误层次结构的代码?

发布时间:2022-07-24

在本教程中,我们将看到如何编写打印 Python 错误层次结构的代码。但是在开始之前,我们应该了解什么是异常?异常是即使我们的代码语法正确也会发生的错误。这些不是无条件致命的,用户在执行代码时得到的错误被称为异常。Python 中有许多内置的异常,在这里,我们将尝试以层次结构打印它们。 为了打印树层次,我们可以使用 Python 的 inspect 模块。inspect 模块用于获取有关对象的信息,如模块、类、方法、函数和程序对象。例如,用户可以使用它来检查类的内容、提取和格式化函数的参数列表。 要构建树层次结构,我们可以使用 inspect.getclasstree() 函数。 语法:

inspect.getclasstree(classes, unique = False)

inspect.getclasstree():用于将给定的类列表排列成嵌套列表的层次结构。当嵌套列表出现时,它将包含从类派生的类,该类的条目将立即进入列表。 示例:

# For printing the hierarchy for inbuilt exceptions:
# First, we will import the inspect module
import inspect as ipt
# Then we will create tree_class function
def tree_class(cls, ind = 0):
      # Then we will print the name of the class
    print ('-' * ind, cls.__name__)
    # now, we will iterate through the subclasses
    for K in cls.__subclasses__():
        tree_class(K, ind + 3)
print ("The Hierarchy for inbuilt exceptions is: ")
# THE inspect.getmro() will return the tuple 
# of class  which is cls's base classes.
#Now, we will build a tree hierarchy 
ipt.getclasstree(ipt.getmro(BaseException))
# function call
tree_class(BaseException)

输出:

The Hierarchy for inbuilt exceptions is: 
 BaseException
---> Exception
---> TypeError
---> MultipartConversionError
---> FloatOperation
---> StopAsyncIteration
---> StopIteration
---> ImportError
---> ModuleNotFoundError
---> ZipImportError
---> OSError
---> ConnectionError
-----> BrokenPipeError
-----> ConnectionAbortedError
-----> ConnectionRefusedError
-----> ConnectionResetError
-------> RemoteDisconnected
---> BlockingIOError
---> ChildProcessError
---> FileExistsError
---> FileNotFoundError
---> IsADirectoryError
---> NotADirectoryError
---> InterruptedError
-----> InterruptedSystemCall
---> PermissionError
---> ProcessLookupError
---> TimeoutError
---> UnsupportedOperation
---> Error
-----> SameFileError
---> SpecialFileError
---> ExecError
---> ReadError
---> herror
---> gaierror
---> timeout
---> SSLError
-----> SSLCertVerificationError
-----> SSLZeroReturnError
-----> SSLWantReadError
-----> SSLWantWriteError
-----> SSLSyscallError
-----> SSLEOFError
---> URLError
-----> HTTPError
-----> ContentTooShortError
---> EOFError
-----> IncompleteReadError
---> RuntimeError
-----> RecursionError
-----> NotImplementedError
-------> StdinNotImplementedError
-------> ZMQVersionError
-----> _DeadlockError
-----> BrokenBarrierError
-----> BrokenExecutor
-----> SendfileNotAvailableError
---> NameError
-----> UnboundLocalError
---> AttributeError
-----> FrozenInstanceError
---> SyntaxError
-----> IndentationError
-------> TabError
---> LookupError
-----> IndexError
-----> KeyError
-------> UnknownBackend
-------> NoSuchKernel
.
.
.
.
---> GeneratorExit
---> SystemExit
---> KeyboardInterrupt
---> CancelledError

结论

在本教程中,我们讨论了如何使用 Python 的 inspect 模块打印层次结构中的异常错误。