Asynchronous IO-coroutine in-depth close, throw

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))

 

Published 89 original articles · won praise 2 · Views 2803

Guess you like

Origin blog.csdn.net/qq_37463791/article/details/105481264