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