[英]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
時,您會誤會。 當生成器函數退出時(而不是在yield
表達式期間),將引發StopIteration
。 因此,捕獲此錯誤的唯一方法是在函數外部執行此操作...
def printtext():
line = yield
print line
if __name__ == '__main__':
p = printtext()
p.send(None)
try:
p.send('Hello, World')
except StopIteration:
pass
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.