Prevent iterator stop on exception

17 views Asked by At

Is there a way to iterate over a complete sequence (that I do not control), even if it raises an exception?

For example, the following code does not work because after an exception is raised a StopIteration follows.

def do(gen):
    it = iter(gen)
    while True:
        try:
            print(next(it))
        except StopIteration:
            break
        except Exception as ex:
            print(ex)

# This is something provided by the user
# For example this:
not_my_gen = (10/x for x in [3, 2, 1, 0, 1, 2, 3])

do(not_my_gen)

Therefore this code results in:

3.3333333333333335
5.0
10.0
division by zero

but I would like to obtain:

3.3333333333333335
5.0
10.0
division by zero
10.0
5.0
3.3333333333333335
0

There are 0 answers