有没有办法阻止StopIteration
异常从不相关的代码中抛出(不必手动捕获它们)?
示例:loop_all
想要循环遍历myiter
迭代器,并在此完成时继续前进。除非some_dangerous_method
或myiter
中的任何其他代码引发StopIteration
,否则此方法有效。
def loop_all():
myiter = myiter()
try:
while True:
next(myiter) # <- I want exactly the StopIteration from this next method
except StopIteration:
pass
def myiter():
some_dangerous_method() # what if this also raises a StopIteration?
for i in some_other_iter():
# here may be more code
yield
有没有办法明确代码应该对StopIteration
作出反应?
答案 0 :(得分:3)
如果您正在调用的函数正在调用next(iter),并且没有处理StopIteration
,那么该函数有一个错误。解决它。
答案 1 :(得分:1)
也许我错过了一些东西,但为什么不简单呢:
def myiter():
try:
some_dangerous_method()
except StopIteration:
pass # or raise a different exception
for i in some_other_iter():
# here may be more code
yield