Skip to Content
Python 技術手冊 第三版
book

Python 技術手冊 第三版

by lex Martelli, Anna Martelli Ravenscroft, Steve Holden
January 2018
Intermediate to advanced content levelIntermediate to advanced
856 pages
17h 17m
Chinese
GoTop Information, Inc.
Content preview from Python 技術手冊 第三版
192
|
5 章 例外
為自訂例外使用多重繼承
每當你必須決定是要提出一個特定的標準例外,例如
AttributeError
,還是你在你模組中定義的一個自訂例外,
那就考慮這種多重繼承的做法,它能讓你兩者兼顧。請確
保你有在說明文件中清楚記載你模組的這個層面,因為這
個技巧並沒有廣泛被使用,你模組的使用者可能沒有如此
預期,除非你清楚且明確的記錄在文件中。
標準程式庫中所使用的其他例外
Python 標準程式庫中的許多模組都定義有它們自己的例外類別,它們與你
自己的模組可以定義的自訂例外類別有相同的效果。一般來說,這種標準
程式庫模組中的所有函式,除了標準階層架構(涵蓋於前面的「標準例外
類別」)中的例外,也可以提出這種類別的例外。舉例來說,在 v2 中,模
socket
提供了類別
socket.error
,它直接衍生自內建類別
Exception
,還
error
的數個子類別
sslerror
timeout
gaierror
herror
模組
socket
中的所有函式與方法,除了標準例外之外,也可以提出類別
socket.error
及其子類別的例外。我們會在本書其餘部分的各處涵蓋這種
例外類別的主要案例,在提供它們的標準程式庫模組的章節中。
錯誤檢查策略
支援例外的多數程式語言只會在少數情況下提出例外。Python 所強調的重
點則不同。Python 會在例外使得程式更為簡單而且更穩健的時候運用它
們,即使那會讓例外變得相當頻繁。
LBYL vs. EAFP
其他語言中一個常見的慣用語(idiom),有時叫做「
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

測試驅動開發|使用 Python

測試驅動開發|使用 Python

Harry J.W. Percival
Linux 内核观测技术BPF

Linux 内核观测技术BPF

David Calavera, Lorenzo Fontana

Publisher Resources

ISBN: 9789864766819