如何在 Python 中检查异常是否包含特定消息

PythonPythonBeginner
立即练习

💡 本教程由 AI 辅助翻译自英文原版。如需查看原文,您可以 切换至英文原版

简介

在这个实验中,你将学习如何在 Python 中探索和访问异常消息,以便有效地调试和处理错误。本实验将指导你创建一个包含 divide 函数的 Python 脚本,该函数使用 try...except 块来捕获除法过程中可能出现的异常。你将观察不同类型的异常,如 ZeroDivisionErrorTypeError,如何生成特定的错误消息。

然后,本实验将演示如何访问异常对象及其类型,以获取有关错误的更详细信息。通过使用不同的输入运行脚本,你将看到异常消息如何为错误原因提供有价值的见解,从而使你能够识别并修复代码中的问题。


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("Python")) -.-> python/ErrorandExceptionHandlingGroup(["Error and Exception Handling"]) python/ErrorandExceptionHandlingGroup -.-> python/catching_exceptions("Catching Exceptions") python/ErrorandExceptionHandlingGroup -.-> python/raising_exceptions("Raising Exceptions") subgraph Lab Skills python/catching_exceptions -.-> lab-559608{{"如何在 Python 中检查异常是否包含特定消息"}} python/raising_exceptions -.-> lab-559608{{"如何在 Python 中检查异常是否包含特定消息"}} end

探索异常消息

在这一步中,你将学习如何在 Python 中探索异常消息。异常消息能提供有关代码中出现问题的宝贵信息,帮助你调试和修复错误。

首先,使用 VS Code 编辑器在你的 ~/project 目录下创建一个名为 exceptions.py 的 Python 文件。

## exceptions.py
def divide(x, y):
    try:
        result = x / y
        print("The result is:", result)
    except Exception as e:
        print("An error occurred:", e)

divide(10, 2)
divide(10, 0)
divide("hello", 5)

在这段代码中:

  • 我们定义了一个 divide(x, y) 函数,用于尝试将 x 除以 y
  • 我们使用 try...except 块来捕获除法过程中可能出现的任何异常。
  • 如果发生异常,我们会打印一条错误消息以及异常对象 e

现在,使用 python 命令运行 exceptions.py 脚本:

python exceptions.py

你应该会看到以下输出:

The result is: 5.0
An error occurred: division by zero
An error occurred: unsupported operand type(s) for /: 'str' and 'int'

如你所见,第一次调用 divide(10, 2) 成功执行并打印了结果。第二次调用 divide(10, 0) 引发了一个 division by zero 异常,该异常被 except 块捕获,并打印了相应的错误消息。第三次调用 divide("hello", 5) 引发了一个 TypeError,因为你不能将字符串除以整数。

现在,让我们修改 exceptions.py 文件,以打印异常的类型:

## exceptions.py
def divide(x, y):
    try:
        result = x / y
        print("The result is:", result)
    except Exception as e:
        print("An error occurred:", type(e), e)

divide(10, 2)
divide(10, 0)
divide("hello", 5)

再次运行脚本:

python exceptions.py

你应该会看到以下输出:

The result is: 5.0
An error occurred: <class 'ZeroDivisionError'> division by zero
An error occurred: <class 'TypeError'> unsupported operand type(s) for /: 'str' and 'int'

这个输出显示了每个发生的异常的类型,为调试提供了更多信息。

访问异常参数

在这一步中,你将学习如何在 Python 中访问与异常相关的参数(args)。异常参数可以提供有关所发生错误的更具体细节。

让我们修改上一步创建的 exceptions.py 文件,以访问并打印异常参数。使用 VS Code 编辑器打开你 ~/project 目录下的 exceptions.py 文件。

## exceptions.py
def divide(x, y):
    try:
        result = x / y
        print("The result is:", result)
    except Exception as e:
        print("An error occurred:", type(e), e.args)

divide(10, 2)
divide(10, 0)
divide("hello", 5)

在这段代码中,我们修改了 except 块以打印 e.argsargs 属性是一个元组,其中包含传递给异常构造函数的参数。

现在,运行 exceptions.py 脚本:

python exceptions.py

你应该会看到以下输出:

The result is: 5.0
An error occurred: <class 'ZeroDivisionError'> ('division by zero',)
An error occurred: <class 'TypeError'> ("unsupported operand type(s) for /: 'str' and 'int'",)

如你所见,输出现在包含了与每个异常相关的参数。对于 ZeroDivisionError,参数是一个包含字符串 'division by zero' 的元组。对于 TypeError,参数是一个包含字符串 "unsupported operand type(s) for /: 'str' and 'int'" 的元组。

让我们再次修改 exceptions.py 文件,以直接访问第一个参数:

## exceptions.py
def divide(x, y):
    try:
        result = x / y
        print("The result is:", result)
    except Exception as e:
        print("An error occurred:", type(e), e.args[0])

divide(10, 2)
divide(10, 0)
divide("hello", 5)

再次运行脚本:

python exceptions.py

你应该会看到以下输出:

The result is: 5.0
An error occurred: <class 'ZeroDivisionError'> division by zero
An error occurred: <class 'TypeError'> unsupported operand type(s) for /: 'str' and 'int'

通过访问 e.args[0],我们可以提取异常的第一个参数,这通常是错误消息中最具描述性的部分。

匹配消息字符串

在这一步中,你将学习如何在 Python 中匹配异常的消息字符串。当你想根据异常消息以不同方式处理特定类型的异常时,这会很有用。

让我们修改你一直在使用的 exceptions.py 文件,专门捕获 ZeroDivisionError 并打印自定义消息。使用 VS Code 编辑器打开你 ~/project 目录下的 exceptions.py 文件。

## exceptions.py
def divide(x, y):
    try:
        result = x / y
        print("The result is:", result)
    except ZeroDivisionError as e:
        print("Cannot divide by zero!")
    except Exception as e:
        print("An error occurred:", type(e), e.args[0])

divide(10, 2)
divide(10, 0)
divide("hello", 5)

在这段代码中:

  • 我们为 ZeroDivisionError 添加了一个特定的 except 块。
  • 如果发生 ZeroDivisionError,我们会打印消息 "Cannot divide by zero!"。
  • 通用的 except Exception as e 块将捕获任何其他异常。

现在,运行 exceptions.py 脚本:

python exceptions.py

你应该会看到以下输出:

The result is: 5.0
Cannot divide by zero!
An error occurred: <class 'TypeError'> unsupported operand type(s) for /: 'str' and 'int'

如你所见,当调用 divide(10, 0) 时,ZeroDivisionError 被特定的 except 块捕获,并打印自定义消息 "Cannot divide by zero!"。divide("hello", 5) 引发的 TypeError 仍被通用的 except 块捕获。

你也可以直接匹配消息字符串,不过通常不建议这样做,因为捕获特定的异常类型更好。以下是具体做法:

## exceptions.py
def divide(x, y):
    try:
        result = x / y
        print("The result is:", result)
    except Exception as e:
        if "division by zero" in str(e):
            print("Cannot divide by zero!")
        else:
            print("An error occurred:", type(e), e.args[0])

divide(10, 2)
divide(10, 0)
divide("hello", 5)

在这段代码中:

  • 我们在通用的 except 块中捕获所有异常。
  • 我们检查字符串 "division by zero" 是否存在于异常对象 e 的字符串表示中。
  • 如果存在,我们打印 "Cannot divide by zero!"。否则,我们打印通用的错误消息。

再次运行脚本:

python exceptions.py

你应该会看到与之前相同的输出:

The result is: 5.0
Cannot divide by zero!
An error occurred: <class 'TypeError'> unsupported operand type(s) for /: 'str' and 'int'

虽然在某些情况下匹配消息字符串可能有用,但通常最好捕获特定的异常类型,因为异常消息可能会改变,从而降低代码的可靠性。

总结

在本次实验中,你探索了 Python 中的异常消息,以了解如何调试和修复错误。你学习了使用 try...except 块在除法运算期间捕获异常,并打印异常对象 e 以查看错误消息。

你还修改了脚本以打印异常的类型,从而进一步了解所遇到错误的性质,例如 ZeroDivisionErrorTypeError。这有助于进行更有针对性的调试和错误处理。