Reputation: 994
Is there any way in Python to continue iterating after exception throwed by iterator/generator? Like in code below, is there any way to skip ZeroDivisionError and continue looping through gener()
without modyfying run()
function?
def gener():
a = [1,2,3,4,0, 5, 6,7, 8, 0, 9]
for i in a:
yield 2/i
def run():
for i in gener():
print i
#---- run script ----#
try:
run()
except ZeroDivisionError:
print 'what magick should i put here?'
Upvotes: 11
Views: 7185
Reputation: 1648
I am not sure, but maybe this suits you better if you want to still understand where errors occured:
In [1]: def gener():
...: a = [1, 2, 0, 3, 4, 5, 6, 7, 8, 9]
...: errors = []
...: for idx, i in enumerate(a):
...: try:
...: yield 2 / i
...: except ZeroDivisionError:
...: errors.append('ZeroDivisionError occured at idx = {}'.for
...: mat(idx))
...: if errors:
...: raise RuntimeWarning('\n'.join(errors))
...:
Upvotes: 1
Reputation: 951
One possible solution is just wrapping the problem code into try ... except block:
def gener():
a = [1,2,3,4,0, 5, 6,7, 8, 0, 9]
for i in a:
try:
div_result = 2/i
except ZeroDivisionError:
div_result = None
yield div_result
Upvotes: 2
Reputation: 336128
The logical place for the try/except
would be the place where the offending calculation takes place:
def gener():
a = [1,2,3,4,0, 5, 6,7, 8, 0, 9]
for i in a:
try:
yield 2/i
except ZeroDivisionError:
pass
Upvotes: 9