Mo2
Mo2

Reputation: 1131

Capture StopIteration Error Message in For Loop

I have code similar to this structure:

def my_gen(some_str):
    if some_str == "":
        raise StopIteration("Input was empty")
    else:
        parsed_list = parse_my_string(some_str)
        for p in parsed_list:
            x, y = p.split()
            yield x, y

for x, y in my_gen()
    # do stuff
    # I want to capture the error message from StopIteration if it was raised manually

Is it possible to do this by using a for loop? I couldn't find a case similar to this elsewhere. If using a for loop isn't possible, what are some other alternatives?

Thanks

Upvotes: 1

Views: 5986

Answers (1)

Burhan Khalid
Burhan Khalid

Reputation: 174624

You cannot do this in a for loop - because a for loop will implicitly catch the StopIteration exception.

One possible way to do this is with an infinite while:

while True:
    try:
        obj = next(my_gen)
    except StopIteration:
        break

print('Done')

Or you can use any number of consumers from the itertools library - have a look at the recipe section at the bottom for examples.

Upvotes: 5

Related Questions