chapter 8.3 in python errors-tutorial: update exception order code example for clarification
Chưa có ai nhận issue này.
- Ngôn ngữ chính
- Python
- Star
- 77.2k
- Fork
- 35.9k
- Chỉ số merge pull request
- Chỉ số pull request đang chờ
Mô tả
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
Hướng dẫn đóng góp
Bắt đầu từ đâu
- Đọc hết issue, rồi đọc hướng dẫn đóng góp của dự án.
- Bình luận trên issue rằng bạn sẽ nhận — tránh hai người làm cùng một việc.
- Fork repository và làm thay đổi trên một nhánh.
- Mở pull request có tham chiếu số hiệu của issue.
Hướng nghiên cứu
Đọc chương 8.3 của hướng dẫn về lỗi trên trang tài liệu được liên kết và xem lại phần thảo luận về đề xuất làm rõ. So sánh các ví dụ hiện tại về thứ tự của exception với các ví dụ được đề xuất; công việc hoàn tất khi chương này thể hiện rõ việc matching và thứ tự ưu tiên kết quả khớp đầu tiên.
Do mô hình lập chỉ mục viết ra từ nội dung của issue.
Đánh giá
- Công nghệ
- python
- Lĩnh vực
- documentation
- Loại issue
- Tài liệu
- Độ khó
- 2/5
- Thời gian dự kiến
- 1-3 giờ
- Mức độ hoạt động
- Đình trệ
- Độ rõ ràng
- Đặc tả rõ ràng
- Mức phù hợp với người mới
- 25/100