第47集:finally语句

学习目标

  • 理解finally语句的作用
  • 掌握finally的使用场景
  • 学会使用finally清理资源
  • 理解try-except-else-finally的完整结构
  • 掌握资源管理的最佳实践

一、finally语句

基本语法

try:
    # 可能出错的代码
    pass
except Exception:
    # 处理异常
    pass
finally:
    # 无论是否异常都会执行
    pass

示例1:finally的基本使用

try:
    print("尝试执行...")
    result = 10 / 0
except ZeroDivisionError:
    print("捕获到除零错误")
finally:
    print("finally块总是执行")

二、finally的执行时机

示例2:正常情况

try:
    print("步骤1")
    print("步骤2")
except Exception as e:
    print(f"异常:{e}")
else:
    print("没有异常")
finally:
    print("finally执行")

示例3:异常情况

try:
    print("步骤1")
    print(10 / 0)
    print("步骤2")
except Exception as e:
    print(f"异常:{e}")
else:
    print("没有异常")
finally:
    print("finally执行")

示例4:return在finally之前

def test_return():
    try:
        return "正常返回"
    except Exception:
        return "异常返回"
    finally:
        print("finally中的代码")

print(test_return())
# 输出:
# finally中的代码
# 正常返回

三、资源清理

示例5:文件操作

def read_file(filename):
    """读取文件"""
    f = None
    try:
        f = open(filename, "r")
        content = f.read()
        return content
    except FileNotFoundError:
        print("文件不存在")
        return None
    finally:
        # 确保文件关闭
        if f:
            f.close()
            print("文件已关闭")

# 使用示例
read_file("example.txt")

示例6:数据库连接

def query_database(sql):
    """查询数据库"""
    conn = None
    try:
        # conn = connect_to_database()
        # result = conn.execute(sql)
        return "查询结果"
    except Exception as e:
        print(f"查询失败:{e}")
        return None
    finally:
        # 确保连接关闭
        if conn:
            # conn.close()
            print("数据库连接已关闭")

四、with语句(推荐)

示例7:使用with自动清理

# ✅ 推荐:使用with
def read_file_with(filename):
    """使用with读取文件"""
    try:
        with open(filename, "r") as f:
            content = f.read()
            return content
    except FileNotFoundError:
        print("文件不存在")
        return None
    # with语句结束后,文件自动关闭

五、课后练习

练习1

使用finally确保文件正确关闭。

练习2

实现一个安全的网络连接函数,使用finally清理资源。

练习3

对比使用finally和使用with的区别。

练习4

编写一个函数,在finally中清理多个资源。

练习5

理解return和finally的执行顺序。

« 上一篇 异常类型与捕获 下一篇 » 自定义异常