聊聊python中的異常嵌套
在Python中,異常也可以嵌套,當(dāng)內(nèi)層代碼出現(xiàn)異常時(shí),指定異常類型與實(shí)際類型不符時(shí),則向外傳,如果與外面的指定類型符合,則異常被處理,直至最外層,運(yùn)用默認(rèn)處理方法進(jìn)行處理,即停止程序,并拋出異常信息。如下代碼:
try: try: raise IndexError except TypeError: print(’get handled’)except SyntaxError: print(’ok’)
運(yùn)行程序:
Traceback (most recent call last):File '<pyshell#47>', line 3, in <module>raise IndexErrorIndexError
再看另一個(gè)被外層try-except捕獲的例子:
try: try: 1/0 finally: print(’finally’)except: print(’ok’)
運(yùn)行:
finallyok
這里值得注意的是except:可以捕獲所有的異常,但實(shí)際上這樣做也有缺點(diǎn),即有時(shí)候會包住預(yù)定的異常。
另外,需要提到的是raise A from B,將一個(gè)異常與另一個(gè)異常關(guān)聯(lián)起來,如果from后面的B沒有被外層捕獲,那么A,B異常都將拋出,例如:
try: 1/0except Exception as E: raise TypeError(’bad’) from E
運(yùn)行:
Traceback (most recent call last):File '<pyshell#4>', line 2, in <module>1/0ZeroDivisionError: division by zero
The above exception was the direct cause of the following exception:
Traceback (most recent call last):File '<pyshell#4>', line 4, in <module>raise TypeError(’bad’) from ETypeError: bad
相反,如果外層捕獲了B:
try: try: 1/0 except Exception as E: raise TypeError from Eexcept TypeError: print(’no’
運(yùn)行:
no
最后,再看看try-finally在嵌套中的表現(xiàn)。
try: try: 1/0 finally: print(’finally’)except: print(’ok’)
運(yùn)行:
finallyok
不管有沒有異常發(fā)生,或者其是否被處理,finally的代碼都要執(zhí)行,如果異常被處理,則停止,如果沒有被處理,向外走,直至最終沒處理,采用默認(rèn)方法處理,上例中,異常在最外層被處理。
try: try: 1/0 except Exception as E: print(’happens’) finally: print(’finally’)except E: print(’get handled’)
運(yùn)行:
happensfinally
異常在內(nèi)部被處理,不再向外傳播。
以上就是聊聊python中的異常嵌套的詳細(xì)內(nèi)容,更多關(guān)于python 異常嵌套的資料請關(guān)注好吧啦網(wǎng)其它相關(guān)文章!
相關(guān)文章:
1. .NET中l(wèi)ambda表達(dá)式合并問題及解決方法2. CSS hack用法案例詳解3. PHP設(shè)計(jì)模式中工廠模式深入詳解4. ASP.NET MVC遍歷驗(yàn)證ModelState的錯(cuò)誤信息5. Ajax實(shí)現(xiàn)表格中信息不刷新頁面進(jìn)行更新數(shù)據(jù)6. asp(vbs)Rs.Open和Conn.Execute的詳解和區(qū)別及&H0001的說明7. 解決AJAX返回狀態(tài)200沒有調(diào)用success的問題8. ThinkPHP5實(shí)現(xiàn)JWT Token認(rèn)證的過程(親測可用)9. JSP數(shù)據(jù)交互實(shí)現(xiàn)過程解析10. ASP 信息提示函數(shù)并作返回或者轉(zhuǎn)向
