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

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

在学习如何打印Python异常之前,我们将学习异常是什么。

当程序无法按照预期的方向执行时,就会发生异常。当发生意外错误或事件时,Python会抛出异常。

异常通常既可以是有效的,也可以是无效的。可以通过程序中的异常以多种方式来处理错误和异常情况。当您怀疑代码可能会出错时,可以使用异常处理技术。这可以防止软件崩溃。

常见的异常

  • IOError(输入输出错误) - 当文件无法打开时

  • ImportError - 当Python找不到模块时

  • ValueError - 当用户按下中断键(通常是Ctrl+C或删除)时

  • EOFError(文件结束错误) - 当input()或raw_input()在未读取任何数据的情况下遇到文件结束条件(EOF)时

Python异常/错误层次结构

Python异常层次结构由各种内置异常组成。该层次结构用于处理各种类型的异常,因为继承的概念也进入了画面。

在Python中,所有内置异常都必须是从BaseException派生的类的实例。

可以通过导入Python的inspect模块来打印此异常或错误层次结构。使用inspect模块,可以进行类型检查、检索方法的源代码、检查类和函数,并检查解释器堆栈。

在这种情况下,可以使用inspect模块中的getclasstree()函数来构建一个树形层次结构。

语法

inspect.getclasstree(classes, unique = False)

示例

使用inspect.getclasstree()可以排列一个嵌套的类列表层级。在嵌套列表中,紧随其后的类所派生出的类也将出现。

# Inbuilt exceptions:
# Import the inspect module
import inspect as ipt
def tree_class(cls, ind = 0):
    print ('-' * ind, cls.__name__)
    for K in cls.__subclasses__():
        tree_class(K, ind + 3)
print ("Inbuilt exceptions is: ")
# THE inspect.getmro() will return the tuple.
# of class which is cls's base classes.
#The next step is to create a tree hierarchy.
ipt.getclasstree(ipt.getmro(BaseException))
# function call
tree_class(BaseException)

输出

在这个示例中,我们只打印了BaseException的层次结构;要打印其他异常的层次结构,请将“Exception”作为参数传递给函数。

Inbuilt exceptions is:
BaseException
--- Exception
------ TypeError
------ StopAsyncIteration
------ StopIteration
------ ImportError
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
------ TokenError
------ StopTokenizing
------ ClassFoundException
------ EndOfBlock
--- GeneratorExit
--- SystemExit
--- KeyboardInterrupt

示例

另一个用于显示Python异常/错误层级的示例如下。在这里,我们尝试使用“Exception”来显示其他异常的层级 –

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

输出

输出如下:

The class hierarchy for built-in exceptions is:
Exception
... TypeError
... StopAsyncIteration
... StopIteration
... ImportError
...... ModuleNotFoundError
...... ZipImportError
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
... Verbose
... TokenError
... StopTokenizing
... EndOfBlock

结论

通过本文,我们学会了如何使用Python的inspect模块来打印异常错误的层次结构。

Camera课程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

办公软件教程

Linux教程

计算机教程

大数据教程

开发工具教程