新聞中心
通過創(chuàng)建一個(gè)新的異常類,程序可以命名它們自己的異常。異常應(yīng)該是典型的繼承自Exception類,通過直接或間接的方式。

融水網(wǎng)站制作公司哪家好,找成都創(chuàng)新互聯(lián)!從網(wǎng)頁(yè)設(shè)計(jì)、網(wǎng)站建設(shè)、微信開發(fā)、APP開發(fā)、響應(yīng)式網(wǎng)站開發(fā)等網(wǎng)站項(xiàng)目制作,到程序開發(fā),運(yùn)營(yíng)維護(hù)。成都創(chuàng)新互聯(lián)從2013年成立到現(xiàn)在10年的時(shí)間,我們擁有了豐富的建站經(jīng)驗(yàn)和運(yùn)維經(jīng)驗(yàn),來(lái)保證我們的工作的順利進(jìn)行。專注于網(wǎng)站建設(shè)就選成都創(chuàng)新互聯(lián)。
以下為與RuntimeError相關(guān)的實(shí)例,實(shí)例中創(chuàng)建了一個(gè)類,基類為RuntimeError,用于在異常觸發(fā)時(shí)輸出更多的信息。
在try語(yǔ)句塊中,用戶自定義的異常后執(zhí)行except塊語(yǔ)句,變量 e 是用于創(chuàng)建Networkerror類的實(shí)例。
class Networkerror(RuntimeError): def __init__(self, arg): self.args = arg
在你定義以上類后,你可以觸發(fā)該異常,如下所示:
try:
raise Networkerror("Bad hostname")
except Networkerror,e:
print e.args在下面這個(gè)例子中,默認(rèn)的__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!'
常見的做法是創(chuàng)建一個(gè)由該模塊定義的異?;惡妥宇?,創(chuàng)建特定的異常類不同的錯(cuò)誤條件。
我們通常定義的異常類,會(huì)讓它比較簡(jiǎn)單,允許提取異常處理程序的錯(cuò)誤信息,當(dāng)創(chuàng)建一個(gè)異常模塊的時(shí)候,常見的做法是創(chuàng)建一個(gè)由該模塊定義的異?;惡妥宇悾鶕?jù)不同的錯(cuò)誤條件,創(chuàng)建特定的異常類:
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
文章標(biāo)題:創(chuàng)新互聯(lián)Python教程:Python中自定義異常的使用舉例
本文鏈接:http://m.fisionsoft.com.cn/article/cddggeh.html


咨詢
建站咨詢
