raise ... from ... 语句

2020年10月29日 / 8次阅读 / Last Modified 2020年10月29日
异常处理

我之前总结过一篇 During handling of the above exception, another exception occurred是如何发生的?

python有这样的语法: raise ... from ...,用这个语法,可以控制异常信息的输出,在连续多个异常发生的情况下,可以更好的控制输出的异常信息内容,方便查找问题。

直接上代码:

$ cat exc.py
try:
    1/0
except Exception as e:
    raise ValueError('denominator is zero') from e

这段代码执行的效果如下:

$ python3 exc.py
Traceback (most recent call last):
  File "exc.py", line 2, in 
    1/0
ZeroDivisionError: division by zero

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

Traceback (most recent call last):
  File "exc.py", line 4, in 
    raise ValueError('denominator is zero') from e
ValueError: denominator is zero

通过 raise ... from ...,异常发生后,输出的信息变成了 The above exception was the direct cause of the following exception,将连续两个异常关联起来了!比较nice。。。

再来一个示例:

$ cat exc.py
try:
    1/0
except Exception as e:
    raise ValueError('denominator is zero') from None

把 raise ... from e,写成 raise ... from None,执行效果如下:

$ python3 exc.py
Traceback (most recent call last):
  File "exc.py", line 4, in 
    raise ValueError('denominator is zero') from None
ValueError: denominator is zero

上一个异常被抑制了,不再输出。

-- EOF --

本文链接:https://www.pynote.net/archives/2688

留言区

《raise ... from ... 语句》有1条留言

电子邮件地址不会被公开。 必填项已用*标注

  • 麦新杰

    PEP0008中有一段说明:Use exception chaining appropriately. In Python 3, "raise X from Y" should be used to indicate explicit replacement without losing the original traceback. When deliberately replacing an inner exception (using "raise X" in Python 2 or "raise X from None" in Python 3.3+), ensure that relevant details are transferred to the new exception (such as preserving the attribute name when converting KeyError to AttributeError, or embedding the text of the original exception in the new exception message). [回复]


前一篇:
后一篇:

More


©Copyright 麦新杰 Since 2019 Python笔记

go to top