在生成器的 finally 块中返回,隐藏异常

在 Pythonreturn文档中它说:“在生成器函数中,该return语句指示生成器已完成并将导致StopIteration引发。”

在下面的示例中,如果我们finally在异常处于活动状态时在块中返回,则会抑制异常并StopIteration引发 a 。是否期望异常被抑制?有没有办法在不抑制块的情况下return从块中取出finally

def hello(do_return):

    try:

        yield 2

        raise ValueError

    finally:

        print('done')

        if do_return:

            return 

没有调用return:


>>> h = hello(False)

>>> next(h)

Out[68]: 2

>>> next(h)

done

Traceback (most recent call last):

  File "E:\Python\Python37\lib\site-packages\IPython\core\interactiveshell.py", line 3326, in run_code

    exec(code_obj, self.user_global_ns, self.user_ns)

  File "<ipython-input-69-31146b9ab14d>", line 1, in <module>

    next(h)

  File "<ipython-input-63-73a2e5a5ffe8>", line 4, in hello

    raise ValueError

ValueError

打电话给return:


>>> h = hello(True)

>>> next(h)

Out[71]: 2

>>> next(h)

done

Traceback (most recent call last):

  File "E:\Python\Python37\lib\site-packages\IPython\core\interactiveshell.py", line 3326, in run_code

    exec(code_obj, self.user_global_ns, self.user_ns)

  File "<ipython-input-72-31146b9ab14d>", line 1, in <module>

    next(h)

StopIteration


largeQ
浏览 110回答 1
1回答

暮色呼如

您的函数没有“正常”返回。您的函数总是通过引发异常而终止。您示例中的关键字return本质上是对 的伪装raise StopIteration,而不是返回本身。当在处理另一个异常 (&nbsp;StopIteration) 时引发异常 ( ) 时,第二个异常优先。ValueError
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python