聊聊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í)候會(huì)包住預(yù)定的異常。
另外,需要提到的是raise A from B,將一個(gè)異常與另一個(gè)異常關(guān)聯(lián)起來(lái),如果from后面的B沒(méi)有被外層捕獲,那么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
不管有沒(méi)有異常發(fā)生,或者其是否被處理,finally的代碼都要執(zhí)行,如果異常被處理,則停止,如果沒(méi)有被處理,向外走,直至最終沒(méi)處理,采用默認(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 異常嵌套的資料請(qǐng)關(guān)注好吧啦網(wǎng)其它相關(guān)文章!
相關(guān)文章:
1. Python實(shí)現(xiàn)迪杰斯特拉算法過(guò)程解析2. Python如何進(jìn)行時(shí)間處理3. Python字符串函數(shù)strip()原理及用法詳解4. python使用ctypes庫(kù)調(diào)用DLL動(dòng)態(tài)鏈接庫(kù)5. html小技巧之td,div標(biāo)簽里內(nèi)容不換行6. 初學(xué)者學(xué)習(xí)Python好還是Java好7. Python使用shutil模塊實(shí)現(xiàn)文件拷貝8. python裝飾器三種裝飾模式的簡(jiǎn)單分析9. python web框架的總結(jié)10. 詳解Python模塊化編程與裝飾器
