如何捕捉协同例程StopIteration异常?

2024-04-26 07:00:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我用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异常为什么会逃逸?在


Tags: namenonesendhelloifmaindefline
1条回答
网友
1楼 · 发布于 2024-04-26 07:00:17

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

相关问题 更多 >