实现说明
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)