python 异常处理

异常

异常是程序在运行过程中发生的错误或异常情况。当出现异常时,程序会中断正常的执行流程,并尝试寻找相应的异常处理代码来处理异常。

Python 中的异常是一个对象,它表示了发生的错误或异常情况。异常对象包含了有关错误的信息,例如错误类型、错误消息和错误发生的位置等。

捕获异常

捕获程序有可能产生的异常

防止程序 由于异常 导致的出错闪退

不一定发生
try 块:包含可能会引发异常的代码。
except 块:用于捕获并处理特定类型的异常。可以有多个 except 块来处理不同类型的异常。
else 块:如果在 try 块中没有发生异常,将执行 else 块中的代码。
finally 块:无论是否发生异常,都会执行 finally 块中的代码。通常用于清理资源或执行一些必须的操作。

python 复制代码
a = input("输入数字")
try:
    b = int(a)
    print(f"你输入的数字{b}")
except Exception as e:
    print("输入错误重新输入")
except ZeroDivisionError as e:
    print("除数为0")
else:
    print("你输入对了")
finally:
    print("正不正确都输出")
print("你好")
python 复制代码
try:
    with open(f"123.txt", "r") as f:
        print(f.read())
except FileNotFoundError as e:
    print("诈骗", e)
print("你好")

因为文件不存在不能读取 所以返回错误

Errno 2\] No such file or directory: '123.txt' ### 自定义异常 ```python class LTone(Exception): def __init__(self, msg): super().__init__(msg) while True: input_str = input("输入数字") try: input_value = int(input_str) if input_value < 1: raise LTone("数值小于1") except LTone as e: print(f"异常为{e}") except ValueError as e: print("不是数字") except Exception as e: print("未知异常") else: if input_value >= 1: if input_value % 2 == 1: print("奇数") else: print("偶数") ``` ![在这里插入图片描述](https://i-blog.csdnimg.cn/direct/b3ada93ba3804b6b8243598bea1f623c.png)

相关推荐
AI探索者13 小时前
LangGraph StateGraph 实战:状态机聊天机器人构建指南
python
AI探索者13 小时前
LangGraph 入门:构建带记忆功能的天气查询 Agent
python
FishCoderh15 小时前
Python自动化办公实战:批量重命名文件,告别手动操作
python
躺平大鹅15 小时前
Python函数入门详解(定义+调用+参数)
python
曲幽16 小时前
我用FastAPI接ollama大模型,差点被asyncio整崩溃(附对话窗口实战)
python·fastapi·web·async·httpx·asyncio·ollama
两万五千个小时20 小时前
落地实现 Anthropic Multi-Agent Research System
人工智能·python·架构
哈里谢顿1 天前
Python 高并发服务限流终极方案:从原理到生产落地(2026 实战指南)
python
用户8356290780512 天前
无需 Office:Python 批量转换 PPT 为图片
后端·python
markfeng82 天前
Python+Django+H5+MySQL项目搭建
python·django
GinoWi2 天前
Chapter 2 - Python中的变量和简单的数据类型
python