Handling Errors
例外回報
int [] a=new int[5]; a[5]=27; 結果輸出 : Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException : 5 at TestErrors.main(Test.java:17)
不論再怎麼有經驗的程式設計師, 都一定會遇到上面的錯誤訊息. 如果你真的沒遇過, 那你一定是白目, 不然就是腦殘
回報ArrayIndexOutOfBoundsException: 5, 因為超出界限
例外如何被丟出
當例外物件產生後, 會被catch區塊截取 . 若無catch區塊, 則會交由方法丟出, 再由上一層的方法接收
例外的型式
例外繼承Throwable. Throwable分Error及Exception二種. 而Exception又分RuntimeException(unchecked Exception)及其他Checked Exception
Error : 無法修復的會誤, 屬非檢驗例外(unchecked), 通常是系統所發出的錯誤
RuntimeException : 典型的程式錯誤, 也屬非檢驗例外
Exception : 可修復的錯誤, 屬檢驗型例外(Checked, 必需有catch區塊)
OutOfMemoryError 是記憶体不足的錯誤訊息, 此錯誤是無法預期及復原. 此例外屬unchecked, 所以無catch區塊, 因為會直接由Console模式下印出錯誤的內容
例外傳遞
public void doThis(){ try { doThat(); } catch (Exception ex) { Logger.getLogger(Chap03_1.class.getName()).log(Level.SEVERE, null, ex); } } public void doThat() throws Exception{ throw new Exception(); }
doThat()使用throws Exception 丟出例外後, 於doThis()的catch block接收, 若doThis()沒有catch block, 則需於doThis() 方法中增加throws Exception修飾字, 然後由main()方法接收。
RuntimeException 及Error二個類別本身是屬於unchecked的, 所以會自動丟出例外, 也不需要catch區塊, 比如ArrayIndexOutOfBoundsException即是此類型態
在NetBeans裏, 如果遇到Checked 的例外時, NetBeans會自動提示錯誤, 並可按Alt+Enter 選擇要使用那種方式處理, 包括增加try/catch區塊, catch statement, 及增加throwss三種
丟出及抓取例外
public static void main(String[] args) { try { openFile(); } catch (IOException ex) { Logger.getLogger(ExceptionTest.class.getName()).log(Level.SEVERE, null, ex); } } public static void openFile() throws IOException{ File test=new File("//test.txt"); if(!file.exists())throw new IOException(); }
new File 會有可能因為路徑錯誤或檔案不存在的錯誤, 所以會丟出IOException 及 SecurityException. SecurityException 是RuntimeException, 屬unchecked, IOException 屬checked Exception, 需自行撰寫catch block
多重 Exceptions and Errors
當一個方法會丟出多個例外時, 比如可能丟出IOException, IllegalArgumentException, ArrayIndexOutOfBoundsException, 則呼叫者必需先catch較小範圍的IOException, 再catch IllegalArgumentException, 最後再catch最大範圍的Exception.
ArrayIndexOutOfBoundsException是unchecked, 所以會自動丟出, 而程式中若有catch Exception, 則此unchecked 也會被抓到.
try{} catch(IOException ioe){} catch(IlleagalArgumentException iae){} catch(Exception e){}
Which one of the following statements is true? A. A RuntimeException must be caught. B. A RuntimeException must be thrown C. A RuntimeException must be caught or thrown. D. A RuntimeException is thrown automatically. Answer : d
Which of the following objects are checked Exceptions? A. All objects of type Throwable B. All objects of type Exception C. All objects of type Exception that are not of type RuntimeException D. All objects of type Error E. All objects of type RuntimeException Answer : C