用戶自定義異常
在程序中可以通過創建新的異常類型來命名自己的異常(Python 類的內容請參見 類
)。異常類通常應該直接或間接的從 Exception 類派生,例如:
>>> class MyError(Exception):
def __init__(self, value): self.value = value
...
...
...
...
...
>>> try:
... raise MyError(2*2)
... except MyError as e:
... print(’My exception occurred, value:’, e.value)
...
My exception occurred, value: 4
>>> raise MyError(’oops!’) Traceback (most recent call last):
File "<stdin>", line 1, in ?
__main__.MyError: ’oops!’
def __str__(self):
return repr(self.value)
在這個例子中,Exception 默認的 __init__() 被覆蓋。新的方式簡單的創建 value
屬性。這就替換了原來創建 args 屬性的方式。
異常類中可以定義任何其它類中可以定義的東西,但是通常為了保持簡單,只在其中 加入幾個屬性信息,以供異常處理句柄提取。如果一個新創建的模塊中需要拋出幾種 不同的錯誤時,一個通常的作法是為該模塊定義一個異常基類,然後針對不同的錯誤 類型派生出對應的異常子類:
class Error(Exception):"""Base class for exceptions in this module.""" pass
class InputError(Error):
"""Exception raised for errors in the input.
Attributes: expression -- input expression in which the error occurred message -- explanation of the error
"""
def __init__(self, expression, message):
self.expression = expression self.message = message
用戶自定義異常