在 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)doneTraceback (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 ValueErrorValueError打电话给return:>>> h = hello(True)>>> next(h)Out[71]: 2>>> next(h)doneTraceback (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
1 回答
暮色呼如
TA贡献1853条经验 获得超9个赞
您的函数没有“正常”返回。您的函数总是通过引发异常而终止。您示例中的关键字return
本质上是对 的伪装raise StopIteration
,而不是返回本身。当在处理另一个异常 ( StopIteration
) 时引发异常 ( ) 时,第二个异常优先。ValueError
添加回答
举报
0/150
提交
取消