Is there a way to prevent StopIteration exceptions from being thrown from unrelated code (without having to catch them manually)?
Example: loop_all wants to loop through the myiter iterator and simply move on when this one has finished. This works unless some_dangerous_method or any other code in myiter raises a 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
Is there a way to make it clear to which StopIteration the code should react to?
If a function you are calling is invoking next(iter), and isn’t dealing with
StopIteration, then that function has a bug. Fix it.