如何捕获协程 StopIteration 异常?

How to catch coroutine StopIteration exception?

我用python2.7.

def printtext():
    try:
        line = yield
        print line
    except StopIteration:
        pass

if __name__ == '__main__':
    p = printtext()
    p.send(None)
    p.send('Hello, World')

我尝试捕获 StopIteration 异常,但它仍然被引发而没有被捕获。

你能给我一些提示,为什么在这种情况下 StopIteration 异常逃脱了吗?

StopIteration 是你误会了。 StopIteration 在生成器函数退出时引发,而不是在 yield 表达式期间引发。因此,捕获它的唯一方法是在函数之外进行...

def printtext():
    line = yield
    print line

if __name__ == '__main__':
    p = printtext()
    p.send(None)
    try:
        p.send('Hello, World')
    except StopIteration:
        pass