The basics of coroutines have been learned, and now learn some other features.After stopping the generator, the next exception will be StopIteration, close to receive exception information through GenertorExit. He is based on BaseExceptions.
def gen_func():
try:
yield "https://www.baidu.com"
except GeneratorExit: # 基于BaseExceptions
pass # 如果这个协程raise Stopiteration的话也不会抛出异常
yield 2 # 如果下面没有的话,close是不会抛异常的
yield 3
return "caicai"
if __name__ =="__main__":
gen = gen_func()
print(next(gen))
gen.close()# 停止这个生成器
print(123)
next(gen)
Go deeper and customize the exception information. If you add an exception, the next yield will be occupied
def gen_func():
try:
yield "https://www.baidu.com"
except Exception: # pass 异常
pass
yield 2
try:
yield 3
except Exception as e:
pass
yield 3
yield 2
return "caicai"
if __name__ =="__main__":
gen = gen_func()
print(next(gen))
gen.throw(Exception,"this is error")# 给上一个添加异常 ,第二个yeild会被占用
print(next(gen))
gen.throw(Exception,"this is error")# 给上一个添加异常,并且下一个yeild会被占用
print(next(gen))