1. 程式人生 > 程式設計 >聊聊python中的異常巢狀

聊聊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 IndexError
IndexError


再看另一個被外層try-except捕獲的例子:

try:
 try:
  1/0
 finally:
  print('finally')
except:
 print('ok')

執行:

finally
ok

這裡值得注意的是except:可以捕獲所有的異常,但實際上這樣做也有缺點,即有時候會包住預定的異常。


另外,需要提到的是raise A from B,將一個異常與另一個異常關聯起來,如果from後面的B沒有被外層捕獲,那麼A,B異常都將丟擲,例如:

try:
 1/0
except Exception as E:
 raise TypeError('bad') from E

執行:

Traceback (most recent call last):
File "<pyshell#4>",line 2,in <module>
1/0
ZeroDivisionError: 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 E

TypeError: bad

相反,如果外層捕獲了B:

try:
 try:
  1/0
 except Exception as E:
  raise TypeError from E
except TypeError:
 print('no'

執行:

no


最後,再看看try-finally在巢狀中的表現。

try:
 try:
  1/0
 finally:
  print('finally')
except:
 print('ok')

執行:

finally
ok

不管有沒有異常發生,或者其是否被處理,finally的程式碼都要執行,如果異常被處理,則停止,如果沒有被處理,向外走,直至最終沒處理,採用預設方法處理,上例中,異常在最外層被處理。

try:
 try:
  1/0
 except Exception as E:
  print('happens')
 finally:
  print('finally')
except E:
 print('get handled')

執行:

happens
finally

異常在內部被處理,不再向外傳播。

以上就是聊聊python中的異常巢狀的詳細內容,更多關於python 異常巢狀的資料請關注我們其它相關文章!