Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to catch coroutine StopIteration exception?

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?

like image 422
shoujs Avatar asked Apr 21 '26 13:04

shoujs


1 Answers

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
like image 85
mgilson Avatar answered Apr 23 '26 01:04

mgilson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!