聊聊python中的異常嵌套
在Python中,異常也可以嵌套,當內層代碼出現異常時,指定異常類型與實際類型不符時,則向外傳,如果與外面的指定類型符合,則異常被處理,直至最外層,運用默認處理方法進行處理,即停止程序,并拋出異常信息。如下代碼:
try: try: raise IndexError except TypeError: print(’get handled’)except SyntaxError: print(’ok’)
運行程序:
Traceback (most recent call last):File '<pyshell#47>', line 3, in <module>raise IndexErrorIndexError
再看另一個被外層try-except捕獲的例子:
try: try: 1/0 finally: print(’finally’)except: print(’ok’)
運行:
finallyok
這里值得注意的是except:可以捕獲所有的異常,但實際上這樣做也有缺點,即有時候會包住預定的異常。
另外,需要提到的是raise A from B,將一個異常與另一個異常關聯起來,如果from后面的B沒有被外層捕獲,那么A,B異常都將拋出,例如:
try: 1/0except Exception as E: raise TypeError(’bad’) from E
運行:
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’
運行:
no
最后,再看看try-finally在嵌套中的表現。
try: try: 1/0 finally: print(’finally’)except: print(’ok’)
運行:
finallyok
不管有沒有異常發生,或者其是否被處理,finally的代碼都要執行,如果異常被處理,則停止,如果沒有被處理,向外走,直至最終沒處理,采用默認方法處理,上例中,異常在最外層被處理。
try: try: 1/0 except Exception as E: print(’happens’) finally: print(’finally’)except E: print(’get handled’)
運行:
happensfinally
異常在內部被處理,不再向外傳播。
以上就是聊聊python中的異常嵌套的詳細內容,更多關于python 異常嵌套的資料請關注好吧啦網其它相關文章!
相關文章: