Python异常处理

异常(exception)是用来管理程序执行期间发生的错误。在程序中,如果你编写了处理该异常的代码,程序将继续运行;如果你未对异常进行处理,程序将停止,并显示一个traceback,其中包含有关异常的报告。

还记得控制流程中有一个门票优惠的代码么(如下)。当你输入的年龄是数字的时候,系统不会报错,但是当你输入了字符串或者其他的内容,程序就好报错。

python 复制代码
# 门票优惠判断
# 6岁以下免票,未满18岁半票,60岁以上免票
TICKET_PRICE = 100
#输入年龄
age = input("输入你的年龄: ")
age = int(age)
#判断门票
if age < 6 or age >= 60:
    print("您可以免门票")
elif  6 <= age <= 18:
    print(f'您可享受半票优惠,支付门票{TICKET_PRICE/2}')
elif 18 <= age <60:
    print(f'您需支付门票{TICKET_PRICE}')
else:
    print(f'您输入的数据错误,请重新输入')
    age = input("输入你的年龄: ")
    age = int(age)

一、异常处理基本语法

try:

代码块

execpt 错误类型:

代码块


加入while循环和异常,改进上面的门票优惠判断代码

python 复制代码
age = input("输入你的年龄: ")
#使用while循环实现错误即重新输入
while True:
    try:
        age = int(age)
        # 判断门票
        if age < 6 or age >= 60:
            print("您可以免门票")
        elif 6 <= age <= 18:
            print(f'您可享受半票优惠,支付门票{TICKET_PRICE / 2}')
        elif 18 <= age < 60:
            print(f'您需支付门票{TICKET_PRICE}')
        else:
            print(f'您输入的数据错误,请重新输入')
            age = input("输入你的年龄: ")
            age = int(age)
        break  # 年龄输入正确就结束循环
    except ValueError:
        print('您输入的年龄不正确')
        age = input("输入你的年龄: ")

二、常见的异常类型

异常类别 主要异常 触发场景
语法错误 SyntaxError, IndentationError 代码语法错误,程序无法运行
名称错误 NameError, UnboundLocalError 使用未定义的变量或函数
类型错误 TypeError 操作或函数应用于不适当类型的对象
值错误 ValueError 函数接收到类型正确但值不合适的参数
索引错误 IndexError 序列索引超出范围
键错误 KeyError 字典中不存在的键
属性错误 AttributeError 访问对象不存在的属性
算术错误 ZeroDivisionError, OverflowError 数学运算错误
导入错误 ImportError, ModuleNotFoundError 导入模块失败
文件错误 FileNotFoundError, PermissionError 文件操作失败
输入输出错误 EOFError, IOError 输入输出操作失败
内存错误 MemoryError, RecursionError 内存不足或递归过深
断言错误 AssertionError assert语句条件为假
系统错误 SystemExit, KeyboardInterrupt 程序退出或用户中断
连接错误 ConnectionError, TimeoutError 网络连接失败
Unicode错误 UnicodeDecodeError, UnicodeEncodeError 字符串编码解码失败

三、异常代码示例

1.SyntaxError (语法错误)

python 复制代码
# 1. 缺少冒号
if True  # ❌ 缺少冒号
    print("Hello")

# 2. 括号不匹配
print("Hello"  # ❌ 缺少右括号

# 3. 无效语法
x = 10
y = 20
if x = y:  # ❌ 应该用 == 而不是 =
    print("相等")

# 4. 错误的缩进
def func():
print("缩进错误")  # ❌ 函数体需要缩进

2.NameError (名称错误)

python 复制代码
# 1. 变量未定义
print(undefined_variable)  # ❌ NameError: name 'undefined_variable' is not defined

# 2. 函数名拼写错误
prnt("Hello")  # ❌ 应该是 print

# 3. 导入的模块未找到
import maths  # ❌ 应该是 math

# 4. 在定义前使用变量
print(x)  # ❌ NameError
x = 10

3. TypeError (类型错误)

python 复制代码
# 1. 类型不匹配的操作
result = "5" + 3  # ❌ TypeError: can only concatenate str (not "int") to str

# 2. 函数调用参数类型错误
len(123)  # ❌ TypeError: object of type 'int' has no len()

# 3. 不可迭代对象的迭代
for i in 123:  # ❌ TypeError: 'int' object is not iterable
    print(i)

# 4. 不可调用的对象
x = 10
x()  # ❌ TypeError: 'int' object is not callable

4.ValueError (值错误)

python 复制代码
# 1. 无效的类型转换
int("abc")  # ❌ ValueError: invalid literal for int() with base 10: 'abc'

# 2. 列表查找不存在的值
numbers = [1, 2, 3]
numbers.index(5)  # ❌ ValueError: 5 is not in list

# 3. 解包数量不匹配
a, b = [1, 2, 3]  # ❌ ValueError: too many values to unpack

# 4. 数学函数无效参数
import math
math.sqrt(-1)  # ❌ ValueError: math domain error

5.IndexError (索引错误)

python 复制代码
# 1. 列表索引超出范围
numbers = [1, 2, 3]
print(numbers[5])  # ❌ IndexError: list index out of range

# 2. 字符串索引超出范围
text = "Hello"
print(text[10])  # ❌ IndexError: string index out of range

# 3. 空列表的索引
empty_list = []
print(empty_list[0])  # ❌ IndexError: list index out of range

# 4. 负索引超出范围
numbers = [1, 2, 3]
print(numbers[-5])  # ❌ IndexError: list index out of range

6.KeyError (键错误)

python 复制代码
# 1. 字典键不存在
person = {'name': 'Alice', 'age': 25}
print(person['city'])  # ❌ KeyError: 'city'

# 2. 集合操作中的键错误
my_set = {1, 2, 3}
my_set.remove(5)  # ❌ KeyError: 5

# 3. 使用不存在的列名(pandas)
import pandas as pd
df = pd.DataFrame({'A': [1, 2], 'B': [3, 4]})
print(df['C'])  # ❌ KeyError: 'C'

7.AttributeError (属性错误)

python 复制代码
# 1. 对象没有该属性
x = 10
print(x.length)  # ❌ AttributeError: 'int' object has no attribute 'length'

# 2. 模块没有该函数
import math
math.sqroot(4)  # ❌ AttributeError: module 'math' has no attribute 'sqroot'

# 3. 字符串方法调用错误
text = "Hello"
text.append("!")  # ❌ AttributeError: 'str' object has no attribute 'append'

# 4. 导入错误导致的属性错误
from datetime import datetim  # ❌ 拼写错误
datetim.now()  # ❌ AttributeError: 'module' object has no attribute 'datetim'

8.ZeroDivisionError (除零错误)

python 复制代码
# 1. 整数除以零
result = 10 / 0  # ❌ ZeroDivisionError: division by zero

# 2. 浮点数除以零
result = 10.0 / 0.0  # ❌ ZeroDivisionError: float division by zero

# 3. 取模运算除零
result = 10 % 0  # ❌ ZeroDivisionError: integer modulo by zero

# 4. 整除运算除零
result = 10 // 0  # ❌ ZeroDivisionError: integer division or modulo by zero

9.FileNotFoundError (文件未找到错误)

python 复制代码
# 尝试打开不存在的文件
try:
    with open("不存在的文件.txt", "r") as f:
        content = f.read()
except FileNotFoundError as e:
    print(f"文件未找到: {e}")
    # 输出: 文件未找到: [Errno 2] No such file or directory: '不存在的文件.txt'

10.EOFError (文件结束错误)

python 复制代码
# 在输入流结束时调用 input()
try:
    # 当标准输入提前结束时
    data = input("请输入: ")
except EOFError as e:
    print(f"输入流已结束: {e}")

# 使用文件时的EOF
try:
    with open("empty.txt", "r") as f:
        while True:
            line = f.readline()
            if not line:
                break
except EOFError as e:
    print(f"文件读取结束: {e}")

11. IOError (输入输出错误)

python 复制代码
# 磁盘空间不足时的写入
try:
    with open("large_file.txt", "w") as f:
        for i in range(1000000):
            f.write(f"Line {i}\n")
except IOError as e:
    print(f"IO错误: {e}")

12.ImportError (导入错误)

python 复制代码
# 1. 导入不存在的模块
try:
    import nonexistent_module
except ImportError as e:
    print(f"导入错误: {e}")

# 2. 从模块导入不存在的对象
try:
    from math import nonexistent_function
except ImportError as e:
    print(f"导入错误: {e}")
相关推荐
tao3556679 小时前
【用AI学前端】准备工作
前端·人工智能
利刃大大10 小时前
【Vue】自定义指令directives && 指令钩子 && IntersectionObserver
前端·javascript·vue.js
共享家952716 小时前
搭建 AI 聊天机器人:”我的人生我做主“
前端·javascript·css·python·pycharm·html·状态模式
Hgfdsaqwr17 小时前
Python在2024年的主要趋势与发展方向
jvm·数据库·python
一晌小贪欢17 小时前
Python 测试利器:使用 pytest 高效编写和管理单元测试
python·单元测试·pytest·python3·python测试
小文数模17 小时前
2026年美赛数学建模C题完整参考论文(含模型和代码)
python·数学建模·matlab
惊讶的猫17 小时前
探究StringBuilder和StringBuffer的线程安全问题
java·开发语言
jmxwzy17 小时前
Spring全家桶
java·spring·rpc
Halo_tjn17 小时前
基于封装的专项 知识点
java·前端·python·算法
Hgfdsaqwr18 小时前
掌握Python魔法方法(Magic Methods)
jvm·数据库·python