try...expect...finally结构
try...expect...finally结构中,finally块无论是否发生异常都会被执行,通常用来释放try块中申请的资源
1 try: 2 a = int(input('请输入一个被除数')) 3 b = int(input('请输入除数')) 4 c = float(a)/float(b) 5 6 except ZeroDivisionError: 7 print('异常,被除数不能为零') 8 except ValueError: 9 print('异常,不能输入字符串!') 10 except NameError: 11 print('异常,变量不存在!') 12 13 except BaseException as e: 14 print(e) 15 16 else: 17 print(c) 18 finally: 19 print('给我继续执行!!') 20 print('程序结束')
1 try: 2 f = open('d:/dddd.text','r') 3 content = f.readline() 4 print(content) 5 6 except: 7 print('文件未找到') 8 9 finally: 10 print('关闭资源') 11 try: 12 f.close() 13 except BaseException as e: 14 print(e) 15 16 print('程序运行结束')