python用戶自定義異常的實例講解
發(fā)布日期:2022-02-20 18:59 | 文章來源:腳本之家
說明
1、程序可以通過創(chuàng)建一個新的異常類來命名它們自己的異常。異常應(yīng)該是典型的繼承自Exception類,直接或間接的方式。
2、異常python有一個大基類,繼承了Exception。因此,我們的定制類也必須繼承Exception。
實例
class ShortInputException(Exception):
def __init__(self, length, atleast):
self.length = length
self.atleast = atleast
def main():
try:
s = input('請輸入 --> ')
if len(s) < 3:
# raise引發(fā)一個你定義的異常
raise ShortInputException(len(s), 3)
except ShortInputException as result:#x這個變量被綁定到了錯誤的實例
print('ShortInputException: 輸入的長度是 %d,長度至少應(yīng)是 %d'% (result.length, result.atleast))
else:
print('沒有異常發(fā)生')
main()
知識點擴展:
自定義異常類型
#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("姓名長度是"+str(self.leng)+",超過長度了")
捕捉用戶手動拋出的異常
#1.捕捉用戶手動拋出的異常,跟捕捉系統(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):
打印異常信息: 姓名長度是7,超過長度了
姓名長度是7,超過長度了
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用戶自定義異常的實例講解的詳細(xì)內(nèi)容,更多關(guān)于python用戶如何自定義異常的資料請關(guān)注本站其它相關(guān)文章!
版權(quán)聲明:本站文章來源標(biāo)注為YINGSOO的內(nèi)容版權(quán)均為本站所有,歡迎引用、轉(zhuǎn)載,請保持原文完整并注明來源及原文鏈接。禁止復(fù)制或仿造本網(wǎng)站,禁止在非maisonbaluchon.cn所屬的服務(wù)器上建立鏡像,否則將依法追究法律責(zé)任。本站部分內(nèi)容來源于網(wǎng)友推薦、互聯(lián)網(wǎng)收集整理而來,僅供學(xué)習(xí)參考,不代表本站立場,如有內(nèi)容涉嫌侵權(quán),請聯(lián)系alex-e#qq.com處理。
相關(guān)文章
關(guān)注官方微信