「python」异常

来源:互联网 发布:一钻淘宝店铺多少钱 编辑:程序博客网 时间:2024/06/05 10:16

异常的传递

1. try嵌套中

import timetry:    f = open('test.txt')    try:        while True:            content = f.readline()            if len(content) == 0:                break            time.sleep(2)            print(content)    finally:        f.close()        print('关闭文件')except:    print("没有这个文件")

运行结果:

In [26]: import time    ...: try:    ...:     f = open('test.txt')    ...:     try:    ...:         while True:    ...:             content = f.readline()    ...:             if len(content) == 0:    ...:                 break    ...:             time.sleep(2)    ...:             print(content)    ...:     finally:    ...:         f.close()    ...:         print('关闭文件')    ...: except:    ...:     print("没有这个文件")    ...: finally:    ...:     print("最后的finally")    ...:     xxxxxxx--->这是test.txt文件中读取到信息^C关闭文件没有这个文件最后的finally

2. 函数嵌套调用中

    def test1():        print("----test1-1----")        print(num)        print("----test1-2----")    def test2():        print("----test2-1----")        test1()        print("----test2-2----")    def test3():        try:            print("----test3-1----")            test1()            print("----test3-2----")        except Exception as result:            print("捕获到了异常,信息是:%s"%result)        print("----test3-2----")    test3()    print("------华丽的分割线-----")    test2()
























原创粉丝点击