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?'
解决方案
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