跳转至

第十章:异常处理

基本语法

try:
    result = 10 / 0
except ZeroDivisionError:
    print("除零错误")

# 捕获多种异常
try:
    file = open('nonexistent.txt')
except FileNotFoundError:
    print("文件不存在")
except PermissionError:
    print("权限不足")
except Exception as e:
    print(f"其他错误: {e}")

# else 和 finally
try:
    result = 10 / 2
except ZeroDivisionError:
    print("除零错误")
else:
    print(f"结果: {result}")  # 无异常时执行
finally:
    print("清理工作")          # 总是执行

抛出异常

def set_age(age):
    if age < 0:
        raise ValueError("年龄不能为负数")
    return age

# 自定义异常
class CustomError(Exception):
    def __init__(self, message, code):
        super().__init__(message)
        self.code = code

raise CustomError("出错了", 500)

异常链

try:
    int("abc")
except ValueError as e:
    raise RuntimeError("转换失败") from e

上下文管理器

# 使用 with 语句
with open('file.txt', 'r') as f:
    content = f.read()
# 自动关闭文件

# 自定义上下文管理器
class Timer:
    def __enter__(self):
        import time
        self.start = time.time()
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        import time
        print(f"耗时: {time.time() - self.start:.2f}s")
        return False  # 不抑制异常

with Timer() as t:
    # 执行代码
    pass

# contextlib 装饰器
from contextlib import contextmanager

@contextmanager
def my_context():
    print("进入")
    yield
    print("退出")

with my_context():
    print("执行中")

常见异常类型

ValueError       # 值错误
TypeError        # 类型错误
KeyError         # 键不存在
IndexError       # 索引越界
FileNotFoundError # 文件不存在
PermissionError  # 权限错误
ZeroDivisionError # 除零错误
AttributeError   # 属性不存在
ImportError      # 导入失败
RuntimeError     # 运行时错误