翻譯:《實用的Python編程》04_04_Defining_exceptions

目錄 | 上一節 (4.3 特殊方法) | 下一節 (5 對象模型)

4.4 定義異常

用戶可以通過類實現自定義異常:

class NetworkError(Exception):
    pass

**異常類始終繼承自 Exception **

它們通常是空類。空類內部使用 pass 表示。

你也可以對異常進行分層:

class AuthenticationError(NetworkError):
     pass

class ProtocolError(NetworkError):
    pass

練習

練習 4.11:自定義異常

通常情況下,為庫定義自己的異常是一種良好的習慣。

這樣可以更容易區分異常是常見編程錯誤觸發的,還是庫為了提示特定問題而有意觸發的。

請修改上次練習中的 create_formatter() 函數,當用戶提供錯誤的格式名時,觸發自定義的 FormatError 異常。

示例:

>>> from tableformat import create_formatter
>>> formatter = create_formatter('xls')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "tableformat.py", line 71, in create_formatter
    raise FormatError('Unknown table format %s' % name)
FormatError: Unknown table format xls
>>>

目錄 | 上一節 (4.3 特殊方法) | 下一節 (5 對象模型)

註:完整翻譯見 //github.com/codists/practical-python-zh