異常(2)----異常處理(try...cache...finally、throws)
二、try...catch異常處理 當執行程式時,可能丟擲異常。可以對可能出現異常的程式捕獲異常並處理。【例1】 當呼叫帶有throws的方法(指可能丟擲非RuntimeException的方法),必須對異常進行捕獲處理或者丟擲。【例2】 如果不對帶有throws的方法(指可能丟擲非RuntimeException的方法)進行異常處理或丟擲,則會報錯。【例3】 try...catch...finally 格式: try{ //被檢測的程式碼。有可能會產生異常的程式碼。 }catch(異常類名 變數){ //異常的處理方式 //這裡面可以任意寫,比如寫迴圈、遍歷、呼叫方法、變數運算等都是可以的。只要有catch就叫處理了異常。 }finally{ //必須要執行程式碼 } 例1:對可能出現異常的程式碼進行異常捕獲,並處理。
執行結果: java.lang.ArrayIndexOutOfBoundsException: 3 at cn.itcast.demo04.Test.main(Test.java:7) aaaa bbbb 例2:當呼叫帶有throws關鍵字的方法時,必須要對異常進行捕獲或者再丟擲去。
執行結果: java.lang.Exception: 陣列不存在 at cn.itcast.demo03.Test.fun(Test.java:19) at cn.itcast.demo03.Test.main(Test.java:8) aaaaa bbbbb 例3:如果不對帶有throws關鍵字的方法進行異常處理或丟擲,則會報錯。
執行結果: Exception in thread "main" java.lang.Error: Unresolved compilation problem: Unhandled exception type Exception at cn.itcast.demo04.Test.main(Test.java:6) 三、throws繼續丟擲異常 當呼叫了帶有throws的方法(指可能丟擲非RuntimeException的方法)時,如果不知道如何進行處理,可以繼續丟擲。【例1】 例1:
執行結果: Exception in thread "main" java.lang.Exception: 傳入的陣列沒有元素 at cn.itcast.demo02.Test.fun(Test.java:16) at cn.itcast.demo02.Test.main(Test.java:6) |