You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何触发PermissionError时Python的finally块未执行?

问题排查与解决
  • 核心问题:代码在进入try块前就触发了异常
    执行f = open("log.txt", "w")时,因为文件已被移除写入权限,这一步直接抛出PermissionError异常,程序直接终止,根本没机会进入try块,所以finally里的代码完全不会执行。

  • 修正方案:将文件打开操作移入try块内,同时处理文件对象未定义的情况,确保finally块能正常执行:

    f = None
    try:
        f = open("log.txt", "w")
        f.write("Hello, World!")
    finally:
        if f is not None:
            f.close()
            print("f has been closed")
    

    不管是文件打开失败还是写入失败,finally块都会执行;添加if f is not None的判断,能避免打开失败时因f未定义导致close()触发新的错误。

  • 更优写法:推荐使用with上下文管理器,它会自动处理文件关闭,无需手动编写finally逻辑:

    try:
        with open("log.txt", "w") as f:
            f.write("Hello, World!")
        print("f has been closed")
    except PermissionError:
        print("无文件写入权限")
    

    with代码块结束后,文件会自动关闭,无论操作是否成功,代码更简洁安全。

内容的提问来源于stack exchange,提问作者Gold Ingot

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.13 23:23:10