python学习笔记(8)异常处理
2021/8/7 17:06:44
本文主要是介绍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)
这篇关于python学习笔记(8)异常处理的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-11-25Python编程基础:变量与类型
- 2024-11-25Python编程基础与实践
- 2024-11-24Python编程基础详解
- 2024-11-21Python编程基础教程
- 2024-11-20Python编程基础与实践
- 2024-11-20Python编程基础与高级应用
- 2024-11-19Python 基础编程教程
- 2024-11-19Python基础入门教程
- 2024-11-17在FastAPI项目中添加一个生产级别的数据库——本地环境搭建指南
- 2024-11-16`PyMuPDF4LLM`:提取PDF数据的神器