class Networkerror(RuntimeError): def __init__(self, arg): self.args = arg
在你定義以上類后,你可以觸發該異常,如下所示:
try: raise Networkerror("Bad hostname") except Networkerror,e: print e.args
在下面這個例子中,默認的__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 "", 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
聲明:本網頁內容旨在傳播知識,若有侵權等問題請及時與本網聯系,我們將在第一時間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com