访问异常参数
在这一步中,你将学习如何在 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.args
。args
属性是一个元组,其中包含传递给异常构造函数的参数。
现在,运行 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]
,我们可以提取异常的第一个参数,这通常是错误消息中最具描述性的部分。