class Networkerror(RuntimeError): def __init__(self, arg): self.args = arg
在你定義以上類(lèi)后,你可以觸發(fā)該異常,如下所示:
try: raise Networkerror("Bad hostname") except Networkerror,e: print e.args
在下面這個(gè)例子中,默認(rèn)的__init__()異常已被我們重寫(xiě)。
>>> 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!'
常見(jiàn)的做法是創(chuàng)建一個(gè)由該模塊定義的異常基類(lèi)和子類(lèi),創(chuàng)建特定的異常類(lèi)不同的錯(cuò)誤條件。
我們通常定義的異常類(lèi),會(huì)讓它比較簡(jiǎn)單,允許提取異常處理程序的錯(cuò)誤信息,當(dāng)創(chuàng)建一個(gè)異常模塊的時(shí)候,常見(jiàn)的做法是創(chuàng)建一個(gè)由該模塊定義的異?;?lèi)和子類(lèi),根據(jù)不同的錯(cuò)誤條件,創(chuàng)建特定的異常類(lèi):
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
聲明:本網(wǎng)頁(yè)內(nèi)容旨在傳播知識(shí),若有侵權(quán)等問(wèn)題請(qǐng)及時(shí)與本網(wǎng)聯(lián)系,我們將在第一時(shí)間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com