← 中文资源

简体中文版本

suppress 只吞预期内的异常

contextlib.suppress 只吞列出的异常类型,其余照常传播:预期内的缺失一行跳过,空 except 的吞异常习惯被显式意图取代,错误面更收敛。

阅读英文原文

实现说明

suppress 只吞列出的类型(KeyError、FileNotFoundError)——块内抛出的 ValueError 照常传播,由 except ValueError 处理器接住。 演示用的数据放在这几个模块级绑定中:config。

使用要点

  • 每一步打印都带着自己的标签:theme:、loaded:、run continues after suppressed errors。

常见问题

suppress 什么异常都吞吗?

不会——只吞列出的类型(KeyError、FileNotFoundError)。块内抛出的 ValueError 照常传播,由 except ValueError 处理器接住。

需要标准库之外的东西吗?

除标准库外不引入任何东西——这个示例没有依赖。 跨调用保留的状态放在这些顶层绑定里:config。

核心语句

with open("definitely-missing.cfg", encoding="utf-8") as handle:
    print("loaded:", handle.readline())
except ValueError as exc:
    print("ValueError escapes suppress:", exc)
with suppress(KeyError):
    print("theme:", config["theme"])

代码示例

from contextlib import suppress

config: dict = {}

# an expected absence: one line says "skip it if it is not there", no bare except needed
with suppress(KeyError):
    print("theme:", config["theme"])

with suppress(FileNotFoundError):
    with open("definitely-missing.cfg", encoding="utf-8") as handle:
        print("loaded:", handle.readline())

print("run continues after suppressed errors")

# only the listed types are swallowed: every other exception propagates untouched
try:
    with suppress(KeyError):
        raise ValueError("not on the list")
except ValueError as exc:
    print("ValueError escapes suppress:", exc)