詳解在Python程序中自定義異常的方法
通過創(chuàng)建一個新的異常類,程序可以命名它們自己的異常。異常應(yīng)該是典型的繼承自Exception類,通過直接或間接的方式。
以下為與RuntimeError相關(guān)的實例,實例中創(chuàng)建了一個類,基類為RuntimeError,用于在異常觸發(fā)時輸出更多的信息。
在try語句塊中,用戶自定義的異常后執(zhí)行except塊語句,變量 e 是用于創(chuàng)建Networkerror類的實例。
class Networkerror(RuntimeError): def __init__(self, arg): self.args = arg
在你定義以上類后,你可以觸發(fā)該異常,如下所示:
try:
raise Networkerror("Bad hostname")
except Networkerror,e:
print e.args
在下面這個例子中,默認(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 "<stdin>", line 1, in ? __main__.MyError: 'oops!'
常見的做法是創(chuàng)建一個由該模塊定義的異?;惡妥宇悾瑒?chuàng)建特定的異常類不同的錯誤條件。
我們通常定義的異常類,會讓它比較簡單,允許提取異常處理程序的錯誤信息,當(dāng)創(chuàng)建一個異常模塊的時候,常見的做法是創(chuàng)建一個由該模塊定義的異常基類和子類,根據(jù)不同的錯誤條件,創(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
相關(guān)文章
Python使用ntplib庫同步校準(zhǔn)當(dāng)?shù)貢r間的方法
NTP網(wǎng)絡(luò)時間協(xié)議其實大家平時或多或少都能接觸到,包括Windows在內(nèi)的操作系統(tǒng)中的很多Internet時間同步功能都是在NTP的基礎(chǔ)上來做,這里我們來看一下Python使用ntplib庫同步校準(zhǔn)當(dāng)?shù)貢r間的方法2016-07-07
python常用數(shù)據(jù)重復(fù)項處理方法
在本篇文章里小編給大家整理的是關(guān)于python常用數(shù)據(jù)重復(fù)項處理方法,需要的朋友們參考下。2019-11-11
pytorch transform數(shù)據(jù)處理轉(zhuǎn)c++問題
這篇文章主要介紹了pytorch transform數(shù)據(jù)處理轉(zhuǎn)c++問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-02-02
Python連接MySQL并使用fetchall()方法過濾特殊字符
這篇文章主要介紹了Python連接MySQL的方法并講解了如何使用fetchall()方法過濾特殊字符,示例環(huán)境為Ubuntu操作系統(tǒng),需要的朋友可以參考下2016-03-03
Django中prefetch_related()函數(shù)優(yōu)化實戰(zhàn)指南
我們可以利用Django框架中select_related和prefetch_related函數(shù)對數(shù)據(jù)庫查詢優(yōu)化,這篇文章主要給大家介紹了關(guān)于Django中prefetch_related()函數(shù)優(yōu)化的相關(guān)資料,需要的朋友可以參考下2022-11-11
python不到50行代碼完成了多張excel合并的實現(xiàn)示例
這篇文章主要介紹了python不到50行代碼完成了多張excel合并的實現(xiàn)示例,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-05-05

