python自定義異常類方式
python自定義異常類
why?
在開發(fā)中一般是禁止寫if···else···的,雖然if···else···很好理解,但那樣顯得代碼不專業(yè),而且有時候會有點冗余!
what?
在python中一般都有一個異常類,這里面有一些自帶的異常,比如:TypeError、ValueError 等,但這些遠遠不能滿足我們的需求,我們時常會定義自己的異常包,然后導入這個包,這樣就可以愉快的開發(fā)了,下面就來展示一下如何定義自己的異常類。
how?
我們想讓函數(shù)返回值不是我們想要的時候就拋出異常,我們完全可以用C語言的if···else··語句,但是為了演示我們是用python的try···except···,raise表示拋出異常,就是在返回值不等于True的時候就拋出異常
#一般都會讓異常繼承這個類,(或者是更高級的BaseException)
#默認大家知道__init__和__str__
class NotEqual(Exception):
? ? def __init__(self, msg):
? ? ? ? self.msg = msg
? ? def __str__(self):
? ? ? ? return self.msg
class OPT():
? ? def test_suit(self, a):
? ? ? ? if a > 10:
? ? ? ? ? ? return True
? ? ? ? else:
? ? ? ? ? ? return False
? ? def test(self):
? ? ? ? try:
? ? ? ? ? ? if ( (True != self.test_suit(5)) or
? ? ? ? ? ? ? ? ?(True != self.test_suit(15)) ):
? ? ? ? ? ? #raise表示拋出異常,后面必須是定義過的異常類,
? ? ? ? ? ? #括號中的內(nèi)容是大家想讓程序打印的內(nèi)容
? ? ? ? ? ? ?? ?raise NotEqual("not equal")?? ?
? ? ? ? except NotEqual as e:
? ? ? ? ? ? print("{}".format(e))
if __name__ == '__main__':
? ? option = OPT()
? ? option.test()
#運行結(jié)果
>>>$ python test.py
>>> ?not equal程序結(jié)尾處的print表示打印到終端(屏幕)的內(nèi)容,在開發(fā)中我們還應當加上python的日志系統(tǒng)(self.logger.debug("……")),讓輸出的內(nèi)容打印到日志中,方便我們定位問題。
注意:
本來True == False不是異常,只是一個非真值,但在這里我們將其處理成了異常,因為python肯定沒有這樣的異常,所以我們必須在開始要定義一個異常類,這樣就可以用了。
python自定義異常捕獲
我們在處理程序異常的時候,可能需要自己定義一些傳入的message,自己定義一些error對應的error_code,在后續(xù)做異常統(tǒng)計的時候可以有自定義的數(shù)據(jù),這時候其實我們可以自定義異常捕獲類。
異常類一般都是繼承自Exception,自定義異常類如下:
class CustomException(Exception): ? ? """ ? ? Customized Exception ? ? Exception raised for errors in the input salary. ? ? Attributes: ? ? ? ? msg ?-- error message ? ? ? ? code -- error attribution ? ? """ ? ? msg, code = "", 0 ? ? def __init__(self, **kwargs): ? ? ? ? for k, v in kwargs.items(): ? ? ? ? ? ? setattr(self, k, v) class UnknownException(CustomException): ? ? code = 100 class ItemClickFailedException(CustomException): ? ? """ ? ? clickable item clicking failed ? ? """ ? ? msg = "failed to click item" ? ? code = 1 class ItemNotFoundException(CustomException): ? ? """ ? ? clickable item not found ? ? """ ? ? msg = "clickable item not found" ? ? code = 2
定義了異常類之后,可以在程序可能出現(xiàn)這些異常的時候,raise這些異常
?def random_click(self, item, items) -> Info: ? ? ? if len(items) == 0: ? ? ? ? ? raise ItemClickFailedException() ? ? ? if not self.is_clickable(item): ? ? ? ? ? raise ItemClickFailedException(msg="item is not visible") ? ? ? item_attr, item_rect = self.click_item(item) ? ? ? return Info(result=True, area=item_attr, x=item_rect.center[0], y=item_rect.center[1], error=[])
并在相應的時候去進行捕獲
def click(self, item, items) -> ClickInfo:
?? ?error_list = []
?? ?try:
?? ??? ?result: ClickInfo = self.random_click(item, items)
?? ?except Exception as e:
?? ??? ?# 此時捕獲到的是具體的異常類實例
?? ??? ?error_list.append(e)
?? ?for error in error_list:
?? ??? ?print("msg={}, code={}".format(error.msg, error.code))如果之前raise的異常是ItemNotFoundException,那將打印出
msg=item is not visible, code=2
如果raise的異常是ItemClickFailedException,那將打印出
msg=failed to click item, code=1
總結(jié)
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
Python 實現(xiàn)局域網(wǎng)遠程屏幕截圖案例
這篇文章主要介紹了Python 實現(xiàn)局域網(wǎng)遠程屏幕截圖案例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2021-03-03
Python實現(xiàn)批量將MP3音頻轉(zhuǎn)為WAV格式詳解
這篇文章主要介紹了通過Python實現(xiàn)將MP3音頻轉(zhuǎn)為WAV格式的方法,文中的示例代碼講解詳細,對我們學習Python有一定幫助,感興趣的可以了解一下2021-12-12

