
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 ...