python学习笔记(8)异常处理
try: pass # 正常执行代码 except Exception as e: pass # 报错信息和异常处理机制 try: with open("vue3.html") as f: data = f.read() print("正常打开") except Exception as e: # Exception是所有异常 print("e",e) # try: # with open("vue3.html") as f: # data = f.read() # print("正常打开") # d = {} # d["a"] # except (FileNotFoundError, KeyError) as e: # 文件没有找到异常 # print("e",e) try: with open("vue3.html") as f: data = f.read() print("正常打开") d = {} d["a"] except FileNotFoundError as e: # 文件没有找到异常 print("e",e) except KeyError as e: # key错误异常 print("e",e) finally: print("无论是否出现异常,一定会执行!") # 自己定义异常 class TooLongException(Exception): def __init__(self, *args: object) -> None: self.len = len def __str__(self): return "输入姓名长度是" + str(self.len) + ",超过长度了" try: name = input("enter your name:") if len(name) > 5: raise TooLongException(len(name)) else: print(name) except TooLongException as error: print("打印异常信息:", error)
posted on 2021-08-07 16:27 torotoise512 阅读(23) 评论(0) 编辑 收藏 举报