有没有办法防止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
代码应该对哪个做出反应?