欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

python自定義異常類方式

 更新時(shí)間:2023年08月12日 08:39:58   作者:編程小段  
這篇文章主要介紹了python自定義異常類方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教

python自定義異常類

why?

在開(kāi)發(fā)中一般是禁止寫(xiě)if···else···的,雖然if···else···很好理解,但那樣顯得代碼不專業(yè),而且有時(shí)候會(huì)有點(diǎn)冗余!

what?

在python中一般都有一個(gè)異常類,這里面有一些自帶的異常,比如:TypeError、ValueError 等,但這些遠(yuǎn)遠(yuǎn)不能滿足我們的需求,我們時(shí)常會(huì)定義自己的異常包,然后導(dǎo)入這個(gè)包,這樣就可以愉快的開(kāi)發(fā)了,下面就來(lái)展示一下如何定義自己的異常類。

how?

我們想讓函數(shù)返回值不是我們想要的時(shí)候就拋出異常,我們完全可以用C語(yǔ)言的if···else··語(yǔ)句,但是為了演示我們是用python的try···except···,raise表示拋出異常,就是在返回值不等于True的時(shí)候就拋出異常

#一般都會(huì)讓異常繼承這個(gè)類,(或者是更高級(jí)的BaseException)
#默認(rèn)大家知道__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表示拋出異常,后面必須是定義過(guò)的異常類,
? ? ? ? ? ? #括號(hào)中的內(nèi)容是大家想讓程序打印的內(nèi)容
? ? ? ? ? ? ?? ?raise NotEqual("not equal")?? ?
? ? ? ? except NotEqual as e:
? ? ? ? ? ? print("{}".format(e))
if __name__ == '__main__':
? ? option = OPT()
? ? option.test()
#運(yùn)行結(jié)果
>>>$ python test.py
>>> ?not equal

程序結(jié)尾處的print表示打印到終端(屏幕)的內(nèi)容,在開(kāi)發(fā)中我們還應(yīng)當(dāng)加上python的日志系統(tǒng)(self.logger.debug("……")),讓輸出的內(nèi)容打印到日志中,方便我們定位問(wèn)題。

注意:

本來(lái)True == False不是異常,只是一個(gè)非真值,但在這里我們將其處理成了異常,因?yàn)閜ython肯定沒(méi)有這樣的異常,所以我們必須在開(kāi)始要定義一個(gè)異常類,這樣就可以用了。

python自定義異常捕獲

我們?cè)谔幚沓绦虍惓5臅r(shí)候,可能需要自己定義一些傳入的message,自己定義一些error對(duì)應(yīng)的error_code,在后續(xù)做異常統(tǒng)計(jì)的時(shí)候可以有自定義的數(shù)據(jù),這時(shí)候其實(shí)我們可以自定義異常捕獲類。

異常類一般都是繼承自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)這些異常的時(shí)候,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=[])

并在相應(yīng)的時(shí)候去進(jìn)行捕獲

def click(self, item, items) -> ClickInfo:
?? ?error_list = []
?? ?try:
?? ??? ?result: ClickInfo = self.random_click(item, items)
?? ?except Exception as e:
?? ??? ?# 此時(shí)捕獲到的是具體的異常類實(shí)例
?? ??? ?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é)

以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。

相關(guān)文章

最新評(píng)論