python 异常处理

当你不知道你的程序会不会出错的时候可以这做:

###用斐波那契生成器来做个例子吧!
def fib(max):
    n,a,b = 0,0,1
    while n < max:
        yield b
        a,b = b,a+b
        n += 1
    return "done"  ##一个函数中只要用了yield这个,它就变成了生成器,不再是函数,后面这个return是返回异常消息
fib = fib(10)
while True:
    try:##异常处理
        x = next(fib)
        print("as:",x)
    except StopIteration as e:##StopIteration错误的类型StopIteration赋值给了e
        print("StopIteration ",e)
        break

 

posted @ 2018-04-25 11:49  Caionk  阅读(113)  评论(0编辑  收藏  举报