java 異常處理方式之一 try—catch——finally
阿新 • • 發佈:2018-11-05
java 異常處理方式之一: try—catch——finally
1. 如何處理Exception的異常
Java提供的是異常處理的抓拋模型為:
- “拋”:當我們執行程式碼時,一旦出現異常,就會在異常的程式碼處生成一個對應的異常型別的物件,並將此物件丟擲。(自動丟擲 / 手動丟擲)
1.1. 一旦丟擲此異常類的物件,那麼程式就終止執行
1.2. 此異常類的物件拋給方法的呼叫者。 - “抓”:抓住上一步丟擲來的異常類的物件。如何抓?即為異常處理的方式
- java 的處理方式之try—catch—finally,抓拋模型
try{
//可能出現異常的程式碼
}catch(Exception1 e1){
//處理的方式1
}catch(Exception2 e2){
//處理的方式2
}finally{
//一定要執行的程式碼
}
2. 注:
- try內宣告的變數,類似於區域性變數,出了try{}語句,就不能被呼叫
- finally是可選的。
- catch語句內部是對異常物件的處理:
getMessage(); printStackTrace();
- 可以有多個catch語句,try中丟擲的異常類物件從上往下去匹配catch中的異常類的型別,一旦滿足就執行catch中的程式碼。執行完,就跳出其後的多條catch語句
- 如果異常處理了,那麼其後的程式碼繼續執行。
- 若catch中多個異常型別是"並列"關係,孰上孰下都可以。
若catch中多個異常型別是"包含"關係,須將子類放在父類的上面,進行處理。否則報錯! - finally中存放的是一定會被執行的程式碼,不管try中、catch中是否仍有異常未被處理,以及是否有return語句。
- try-catch是可以巢狀的。
3.dome
- 對於執行時異常來說,可以不顯式的進行處理。
- 對於編譯時異常來說,必須要顯式的進行處理。
- 程式碼
public class TestException1 { // 編譯時異常 @Test public void test6() { FileInputStream fis = null; try { fis = new FileInputStream(new File("hello.txt")); int b; while ((b = fis.read()) != -1) { System.out.print((char) b); } } catch (FileNotFoundException e1) { System.out.println("檔案找不到了!"); } catch (IOException e1) { System.out.println(e1.getMessage()); } finally { try { fis.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } // 常見的執行時異常 // 4.空指標異常:NullPointerExcetion @Test public void test5() { // Person p = new Person(); // p = null; // System.out.println(p.toString()); try { String str = new String("AA"); str = null; System.out.println(str.length()); } catch (Exception e) { // e.printStackTrace(); System.out.println("出現空指標的異常了"); } } // 3.型別轉換異常:ClassCastException @Test public void test4() { try { Object obj = new Date(); String str = (String) obj; } catch (ClassCastException e) { System.out.println("出現型別轉換的異常了"); //System.out.println(10 / 0); } catch (Exception e) { e.printStackTrace(); } finally { System.out.println("hello!美女!"); } // String str1 = (String)new Date(); } // 2.算術異常:ArithmeticException @Test public void test3() { try { int i = 10; System.out.println(i / 0); } catch (Exception e) { // e.printStackTrace(); System.out.println(e.getMessage()); } } // 1.陣列下標越界的異常:ArrayIndexOutOfBoundsException @Test public void test2() { try { int[] i = new int[10]; // System.out.println(i[10]); System.out.println(i[-10]); } catch (Exception e) { System.out.println("出現異常了!"); } } @Test public void test1() { Scanner s = new Scanner(System.in); try { int i = s.nextInt(); System.out.println(i); } catch (InputMismatchException e) { System.out.println("出現型別不匹配的異常了!"); } } }