在生成器的 finally 块中返回,隐藏异常
Returning within a finally block in a generator, hides the exception
在 Python return
文档中 it says:“在生成器函数中,return
语句表示生成器已完成并将导致 StopIteration
被提出。
在下面的示例中,如果我们在 finally
块中 return 而异常处于活动状态,则异常将被抑制并引发 StopIteration
。是否期望异常被抑制?有没有办法从 finally
块中 return
而不抑制它?
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
您的函数没有“正常”return。您的函数总是通过引发异常而终止。您示例中的关键字 return
本质上是 raise StopIteration
的伪装,而不是 return 本身。如果在处理另一个异常 (ValueError
) 时引发异常 (StopIteration
),则第二个异常优先。
在 Python return
文档中 it says:“在生成器函数中,return
语句表示生成器已完成并将导致 StopIteration
被提出。
在下面的示例中,如果我们在 finally
块中 return 而异常处于活动状态,则异常将被抑制并引发 StopIteration
。是否期望异常被抑制?有没有办法从 finally
块中 return
而不抑制它?
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
您的函数没有“正常”return。您的函数总是通过引发异常而终止。您示例中的关键字 return
本质上是 raise StopIteration
的伪装,而不是 return 本身。如果在处理另一个异常 (ValueError
) 时引发异常 (StopIteration
),则第二个异常优先。