gpt4 book ai didi

Python:如何捕获异常链的内部异常?

转载 作者:太空宇宙 更新时间:2023-11-03 12:27:09 26 4
gpt4 key购买 nike

考虑这个简单的例子:

def f():
try:
raise TypeError
except TypeError:
raise ValueError

f()

f() 执行后抛出 ValueError 时,我想捕获 TypeError 对象。有可能吗?

如果我执行函数 f() 然后 python3 打印到 stderr 异常链 (PEP-3134) 的所有引发的异常

Traceback (most recent call last):
File "...", line 6, in f
raise TypeError
TypeError

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "...", line 11, in <module>
f()
File "...", line 8, in f
raise ValueError
ValueError

所以我会得到异常链的所有异常列表检查异常链中是否存在某种类型的异常(上例中的TypeError)。

最佳答案

Python 3 在异常处理方面有一个漂亮的语法增强。不要直接引发 ValueError,您应该从捕获的异常中引发它,即:

try:
raise TypeError('Something awful has happened')
except TypeError as e:
raise ValueError('There was a bad value') from e

注意回溯之间的区别。这个使用 raise from 版本:

Traceback (most recent call last):
File "/home/user/tmp.py", line 2, in <module>
raise TypeError('Something awful has happened')
TypeError: Something awful has happened

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
File "/home/user/tmp.py", line 4, in <module>
raise ValueError('There was a bad value') from e
ValueError: There was a bad value

虽然结果看起来很相似,但实际上却大不相同! raise from 保存了原始异常的上下文,并允许人们追溯所有异常链回 - 这对于简单的 raise 是不可能的。

要获得原始异常,您只需引用新异常的 __context__ 属性,即

try:
try:
raise TypeError('Something awful has happened')
except TypeError as e:
raise ValueError('There was a bad value') from e
except ValueError as e:
print(e.__context__)
>>> Something awful has happened

希望这就是您正在寻找的解决方案。

有关详细信息,请参阅 PEP 3134 -- Exception Chaining and Embedded Tracebacks

关于Python:如何捕获异常链的内部异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38824798/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com