久久r热视频,国产午夜精品一区二区三区视频,亚洲精品自拍偷拍,欧美日韩精品二区

您的位置:首頁(yè)技術(shù)文章
文章詳情頁(yè)

python用戶自定義異常的實(shí)例講解

瀏覽:2日期:2022-07-28 08:15:15
說明

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

2、異常python有一個(gè)大基類,繼承了Exception。因此,我們的定制類也必須繼承Exception。

實(shí)例

class ShortInputException(Exception): def __init__(self, length, atleast):self.length = lengthself.atleast = atleastdef main(): try:s = input(’請(qǐng)輸入 --> ’)if len(s) < 3: # raise引發(fā)一個(gè)你定義的異常 raise ShortInputException(len(s), 3) except ShortInputException as result:#x這個(gè)變量被綁定到了錯(cuò)誤的實(shí)例print(’ShortInputException: 輸入的長(zhǎng)度是 %d,長(zhǎng)度至少應(yīng)是 %d’% (result.length, result.atleast)) else:print(’沒有異常發(fā)生’)main()

知識(shí)點(diǎn)擴(kuò)展:

自定義異常類型

#1.用戶自定義異常類型,只要該類繼承了Exception類即可,至于類的主題內(nèi)容用戶自定義,可參考官方異常類class TooLongExceptin(Exception): 'this is user’s Exception for check the length of name ' def __init__(self,leng): self.leng = leng def __str__(self): print('姓名長(zhǎng)度是'+str(self.leng)+',超過長(zhǎng)度了')

捕捉用戶手動(dòng)拋出的異常

#1.捕捉用戶手動(dòng)拋出的異常,跟捕捉系統(tǒng)異常方式一樣def name_Test(): try: name = input('enter your naem:') if len(name)>4: raise TooLongExceptin(len(name)) else : print(name) except TooLongExceptin,e_result: #這里異常類型是用戶自定義的 print('捕捉到異常了') print('打印異常信息:',e_result) #調(diào)用函數(shù),執(zhí)行name_Test()==========執(zhí)行結(jié)果如下:==================================================enter your naem:aaafsdf捕捉到異常了Traceback (most recent call last):打印異常信息: 姓名長(zhǎng)度是7,超過長(zhǎng)度了姓名長(zhǎng)度是7,超過長(zhǎng)度了 File 'D:/pythoyworkspace/file_demo/Class_Demo/extion_demo.py', line 16, in name_Test raise TooLongExceptin(len(name))__main__.TooLongExceptin: <exception str() failed> During handling of the above exception, another exception occurred: Traceback (most recent call last): File 'D:/pythoyworkspace/file_demo/Class_Demo/extion_demo.py', line 26, in <module> name_Test() File 'D:/pythoyworkspace/file_demo/Class_Demo/extion_demo.py', line 22, in name_Test print('打印異常信息:',e_result)TypeError: __str__ returned non-string (type NoneType)

以上就是python用戶自定義異常的實(shí)例講解的詳細(xì)內(nèi)容,更多關(guān)于python用戶如何自定義異常的資料請(qǐng)關(guān)注好吧啦網(wǎng)其它相關(guān)文章!

標(biāo)簽: Python 編程
相關(guān)文章:
主站蜘蛛池模板: 凤冈县| 汉中市| 溧水县| 分宜县| 游戏| 凤翔县| 济阳县| 张家界市| 河北区| 罗源县| 徐水县| 盱眙县| 合水县| 时尚| 西昌市| 梅河口市| 阜平县| 集安市| 伊川县| 两当县| 阳高县| 辰溪县| 巩留县| 新绛县| 延津县| 红河县| 南投市| 香港| 弋阳县| 沾益县| 汉阴县| 红桥区| 盐津县| 浠水县| 彭州市| 星子县| 鄂州市| 灵山县| 阿城市| 霍林郭勒市| 五原县|