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

时间:2016-08-08 08:46:12

标签: python python-3.x exception-handling

考虑一个简单的例子:

eval

我希望在执行def f(): try: raise TypeError except TypeError: raise ValueError f() 后抛出TypeError时捕获ValueError对象。有可能吗?

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

f()

所以我会得到异常链的所有异常列表,检查异常链中是否存在某种类型的异常(上例中为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 )。

1 个答案:

答案 0 :(得分:10)

Python 3在异常处理方面具有漂亮的语法增强功能。您应该从捕获的异常中提取它,而不是明显地引发ValueError,即:

onKeyPress="return ValidateAlpha1(event);"

注意回溯之间的区别。这个使用onKeyPress="return ValidateAlpha1(event);" 版本:

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

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

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