I use python2.7.
def printtext():
try:
line = yield
print line
except StopIteration:
pass
if __name__ == '__main__':
p = printtext()
p.send(None)
p.send('Hello, World')
I try to catch StopIteration exception but it is still raised without being caught.
Could you please give me some hint why the StopIteration exception escaped in this case?
You're misunderstanding when StopIteration is raised. StopIteration is raised when a generator function exits, not during a yield expression. As such, the only way to catch this is to do it outside the function...
def printtext():
line = yield
print line
if __name__ == '__main__':
p = printtext()
p.send(None)
try:
p.send('Hello, World')
except StopIteration:
pass
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With