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 技術手冊 第三版
190
|
5 章 例外
自訂的例外類別
你可以擴充任何的標準例外類別來定義你自己的例外類別。通常,這樣的
子類別除了加上一個 docstring 以外不會做任何事:
class InvalidAttribute(AttributeError):
"""Used to indicate attributes that could never be valid"""
任何空的類別或函式都應該有一個
docstring
而非
pass
如前面的「pass 述句」中所涵蓋的,你不需要一個
pass
述句來構成一個類別的主體,只要有 docstring(你應該永
遠都寫,以記載類別的用途)就足以讓 Python 滿意。所
有「空」類別(不管它們是不是例外類別)的最佳實務做
法,就跟所有「空」函式一樣,都是帶有一個 docstring
而非
pass
述句。
根據
try/except
的語意,提出像
InvalidAttribute
這樣的自訂例外類別幾
乎等同於提出它的標準例外超類別
AttributeError
。處理
AttributeError
任何
except
子句也都能處理
InvalidAttribute
。此外,知道你自訂例外類
InvalidAttribute
的客戶端程式碼也能特別處理它,而不用應付不準備
處理的其他 AttributeError 情況。舉例來說:
class SomeFunkyClass(object):
"""much hypothetical functionality snipped"""
def ...
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