在 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個贊
您的函數沒有“正?!狈祷亍D暮瘮悼偸峭ㄟ^引發異常而終止。您示例中的關鍵字return
本質上是對 的偽裝raise StopIteration
,而不是返回本身。當在處理另一個異常 ( StopIteration
) 時引發異常 ( ) 時,第二個異常優先。ValueError
添加回答
舉報
0/150
提交
取消