GeneratorExit in Python generator

前端 未结 3 432
孤城傲影
孤城傲影 2020-12-30 11:42

I wrote a test program about Python generator. But I got an error that is not expected. And I don\'t know how to explain it. Let me show you the code:

def co         


        
3条回答
  •  余生分开走
    2020-12-30 12:24

    When the generator object is garbage-collected at the end of your program, its close() method is called, and this raises the GeneratorExit exception inside the generator. Normally this is not caught and causes the generator to exit.

    Since you catch the exception and proceed to yield another value, this causes a RuntimeError. If you catch the GeneratorExit exception you need to either reraise it, or exit the function without yielding anything else.

提交回复
热议问题