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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.