如果你需要自訂異常的話,可以從Exception類派生。 在這個例子中,預設的__init__()異常已被我們重寫。
>>> class MyError(Exception):
... def __init__(self, value):
... self.value = value
... def __str__(self):
... return repr(self.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!'
常見的做法是建立一個由該模組定義的異常基類和子類,建立特定的異常類不同的錯誤條件。
我們通常定義的異常類,會讓它比較簡單,允許提取例外處理常式的錯誤資訊,當建立一個異常模組的時候,常見的做法是建立一個由該模組定義的異常基類和子類,根據不同的錯誤條件,建立特定的異常類:
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
class TransitionError(Error):
"""Raised when an operation attempts a state transition that's not
allowed.
Attributes:
previous -- state at beginning of transition
next -- attempted new state
message -- explanation of why the specific transition is not allowed
"""
def __init__(self, previous, next, message):
self.previous = previous
self.next = next
self.message = message