def my_generator(): try: yield 'something' except ValueError: yield 'dealing with the exception' finally: # closeとthrowのどちらを呼び出しても一箇所で例外をつかまえて処理する print("ok let's clean") gen = my_generator() print next(gen) # something print gen.throw(ValueError('mean mean mean')) # dealing with the exception 例外を送り込む print gen.close() # ok let's clean GeneratorExitを発生させる # None print next(gen) # StopIteration