转载地址 https://blog.csdn.net/hedan2013/article/details/72810653
当一个生成器对象被销毁时,会抛出一个GeneratorExit异常。请看下面的代码。
- def myGenerator():
- try:
- yield 1
- except GeneratorExit:
- print "myGenerator exited"
- gen = myGenerator()
- print gen.next()
def myGenerator(): try: yield 1 except GeneratorExit: print "myGenerator exited"gen = myGenerator()print gen.next()输出结果为
- 1
- myGenerator exited
1myGenerator exited
上面代码的运行逻辑如下: 当调用到gen.next()方法时,会执行生成器对象方法的yield语句。此后,主程序结束,系统会自动产生一个GeneratorExit异常,被生成器对象方法的Except语句块截获。
而GeneratorExit异常产生的时机,是在生成器对象被销毁之前。为了验证这点,请看下面的代码。
- def myGenerator():
- try:
- yield 1
- yield 2
- except GeneratorExit:
- print "myGenerator exited"
- gen = myGenerator()
- print gen.next()
- del gen
- print "Main caller exited"
def myGenerator(): try: yield 1 yield 2 except GeneratorExit: print "myGenerator exited"gen = myGenerator()print gen.next()del genprint "Main caller exited"
输出结果
- 1
- myGenerator exited
- Main caller exited
1myGenerator exitedMain caller exited
值得一提的是,GeneratorExit异常只有在生成器对象被激活后,才有可能产生。更确切的说,需要至少调用一次生成器对象的next方法后,系统才会产生GeneratorExit异常。请看下面的代码。
- def myGenerator():
- try:
- yield 1
- yield 2
- except GeneratorExit:
- print "myGenerator exited"
- gen = myGenerator()
- del gen
- print "Main caller exited"
def myGenerator(): try: yield 1 yield 2 except GeneratorExit: print "myGenerator exited"gen = myGenerator()del genprint "Main caller exited"其输出结果如下:
- Main caller exited
Main caller exited
在上面的示例中,我们都显式地捕获了GeneratorExit异常。如果该异常没有被显式捕获,生成器对象也不会把该异常向主程序抛出。因为GeneratorExit异常定义的初衷,是方便开发者在生成器对象调用结束后定义一些收尾的工作,如释放资源等。