python怎么自定義捕獲錯(cuò)誤
異常捕捉:
try: XXXXX1 raise Exception(“xxxxx2”) except (Exception1,Exception2,……): xxxx3else: xxxxx4finally: xxxxxxx5
1.raise 語句可以自定義報(bào)錯(cuò)信息,如上。
2. raise后的語句是不會被執(zhí)行了,因?yàn)橐呀?jīng)拋出異常,控制流將會跳到異常捕捉模塊。
3. except 語句可以一個(gè)except后帶多個(gè)異常,也可以用多個(gè)語句捕捉多個(gè)異常,分別做不同處理。
4. except語句捕捉的異常如果沒有發(fā)生,那么except里的語句塊是不被執(zhí)行的。而是執(zhí)行else里的語句
5. 在上面語句中try/except/else/finally所出現(xiàn)的順序必須是try?>except X?>except?>else?>finally,即所有的except必須在else和finally之前,else(如果有的話)必須在finally之前,而except X必須在except之前。否則會出現(xiàn)語法錯(cuò)誤。
6.else和finally都是可選的.
7.在上面的完整語句中,else語句的存在必須以except X或者except語句為前提,如果在沒有except語句的try block中使用else語句會引發(fā)語法錯(cuò)誤。
異常參數(shù)輸出:
try: testRaise()except PreconditionsException as e: #python3的寫法,必須用as print (e)
自定義異常,只需自定義異常類繼承父類Exception。在自定義異常類中,重寫父類init方法。
class DatabaseException(Exception): def __init__(self,err=’數(shù)據(jù)庫錯(cuò)誤’): Exception.__init__(self,err)class PreconditionsException(DatabaseException): def __init__(self,err=’PreconditionsErr’): DatabaseException.__init__(self,err)def testRaise(): raise PreconditionsException()try: testRaise()except PreconditionsException as e: print (e)
注意:PreconditonsException又是DatabaseException的子類。
所以如果,raise PreconditionException的話,用兩個(gè)異常類都可以捕捉。
但是, 如果是raise DatabaseException, 用PreconditonsException是捕捉不到的。
實(shí)例補(bǔ)充:
python自定義異常捕獲異常處理異常
def set_inf(name,age): if not 0 < age < 120: raise ValueError(’超出范圍’) else: print(’%s is %s years old’ % (name,age))def set_inf2(name,age): assert 0 < age < 120,’超出范圍’ print(’%s is %s years old’ % (name,age))if __name__ == ’__main__’: try: set_inf(’bob’,200) except ValueError as e: print(’無效值:’,e) set_inf2(’bob’,200)
到此這篇關(guān)于python怎么自定義捕獲錯(cuò)誤的文章就介紹到這了,更多相關(guān)python自定義捕獲錯(cuò)誤的方法內(nèi)容請搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
1. 小技巧處理div內(nèi)容溢出2. UDDI FAQs3. jsp實(shí)現(xiàn)登錄界面4. 解析原生JS getComputedStyle5. .NET SkiaSharp 生成二維碼驗(yàn)證碼及指定區(qū)域截取方法實(shí)現(xiàn)6. PHP循環(huán)與分支知識點(diǎn)梳理7. 怎樣才能用js生成xmldom對象,并且在firefox中也實(shí)現(xiàn)xml數(shù)據(jù)島?8. PHP字符串前后字符或空格刪除方法介紹9. ASP刪除img標(biāo)簽的style屬性只保留src的正則函數(shù)10. jsp+servlet實(shí)現(xiàn)猜數(shù)字游戲
