chapter 8.3 in python errors-tutorial: update exception order code example for clarification
还没有人认领这个 Issue。
- 主要语言
- Python
- 星标
- 77.2k
- 派生
- 35.9k
- PR 合并指标
- PR 指标待抓取
描述
Documentation
The errors tutorial, chapter 8.3 contains an example that could be improved, as the highlighted subjects (exception ordering and matching) are not that easy to follow: https://docs.python.org/3/tutorial/errors.html
The issue was discussed here:
https://discuss.python.org/t/exception-tutorial-confusion/97456
Original:
A class in an except clause matches exceptions which are instances of the class itself or one of its derived classes (but not the other way around — an except clause listing a derived class does not match instances of its base classes). For example, the following code will print B, C, D in that order:
class B(Exception):
pass
class C(B):
pass
class D(C):
pass
for cls in [B, C, D]:
try:
raise cls()
except D:
print("D")
except C:
print("C")
except B:
print("B")
Note that if the except clauses were reversed (with except B first), it would have printed B, B, B — the first matching except clause is triggered.
Suggested Update
Code examples created by Guido van Rossum, see https://discuss.python.org/t/exception-tutorial-confusion/97456/5.
A class in an except clause matches exceptions which are instances of the class itself or one of its derived classes (but not the other way around — an except clause listing a derived class does not match instances of its base classes).
For example, the following code will print B, C in that order:
class B(Exception):
pass
class C(B):
pass
for cls in [B, C]:
try:
raise cls()
except C:
# Matches C but not B.
print("C")
except B:
# Matches B; not reached for C.
print("B")
Note that if the except clauses were reversed (with except B first), it would have printed B, B — the first matching except clause is triggered, like in the following example:
for cls in [B, C]:
try:
raise cls()
except B:
# Matches B and C both.
print("B")
except C:
# Not reached (the previous clause ate B and C)
print("C")
Linked PRs
- gh-136257
贡献指南
从这里开始
- 先读完整个 Issue,再读项目的贡献指南。
- 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
- Fork 仓库,在一个分支上完成修改。
- 提交 Pull Request,并在描述里引用这个 Issue 编号。
调研方向
阅读链接文档页面上的错误教程第 8.3 章,并查看关于拟议澄清的讨论。将当前的异常顺序示例与建议的示例进行比较;当本章能够清楚地演示匹配和首次匹配顺序时,工作就完成了。
由索引模型根据 Issue 内容生成。
评估
- 技术栈
- python
- 领域
- documentation
- Issue 类型
- 文档
- 难度
- 2/5
- 预计耗时
- 1-3 小时
- 活跃度
- 停滞
- 描述清晰度
- 描述清楚
- 新手友好度
- 25/100