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

问题描述

在Python return文档it says中:“在生成函数中,return语句表明生成器已完成,并且将引起stopiteration升高。”

在下面的示例中,如果我们在一个异常处于活动状态的情况下返回finally块,则会抑制该异常并改为引发stopiteration。是否希望异常被抑制?有没有一种方法可以在不抑制的情况下从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",self.user_ns)
  File "<ipython-input-72-31146b9ab14d>",in <module>
    next(h)
stopiteration

解决方法

您的函数没有“正常”返回。您的函数总是通过引发异常来终止。您的示例中的关键字return本质上是raise StopIteration的伪装,而不是这样的返回。如果在处理另一个异常(StopIteration)时引发异常(ValueError),则以第二个异常为准。