try/catch/finally測試結(jié)論:
1、如果某個異常發(fā)生的時候沒有在任何地方捕獲它,程序就會終止執(zhí)行,并在控制臺上顯示異常信息 2、不管是否有異常被捕獲,finally子句中的代碼都會執(zhí)行 3、當代碼拋出一個異常時,就會終止對方法中剩余代碼的處理,并退出這個方法 4、finally后面的代碼被執(zhí)行的條件: a、代碼沒有拋出異常 或者b、代碼拋出異常被捕獲,而且捕獲的時候沒有再拋出異常 5、建議用try/catch和try/finally語句塊,前者是將異常攔截;而后者是為了將異常送出去,并執(zhí)行所需代碼 6、finally優(yōu)先于try中的return語句執(zhí)行,所以finally中,如果有return,則會直接返回,而不是調(diào)用try中的return;catch中的return也是一樣,也就是說,在return之前,肯定會先調(diào)用finally中的return 例1: // 測試捕獲異常后,再次拋出異常,不會執(zhí)行finally后面的語句// 1 // 因為編譯就通不過,直接報:unreacchable statement private static String testTryCatch() throws Exception { try { throw new Exception(); } catch (Exception e) { // 捕獲異常后再次拋出異常 throw new Exception(); } finally { System.out.println("finally"); } return "after finally"; // 1 } 例2: // 測試異常被捕獲,會繼續(xù)執(zhí)行finally后面的語句// 1 private static void testTryCatch() { try { throw new Exception(); } catch (Exception e) { e.printStackTrace(); System.out.println("exception"); } finally { System.out.println("finally"); } System.out.println("after finally"); // 1 } // 輸出: java.lang.Exception at Main.testTryCatch(Main.java:39) at Main.main(Main.java:10) exception finally after finally 例3: // 測試finally中的return優(yōu)先級最高 private static String testTryCatch() { try { throw new Exception(); } catch (Exception e) { e.printStackTrace(); return "exception"; // 2 } finally { return "finally"; // 1 } } // 輸出 最后返回的結(jié)果是// 1中的"finally" 例4: public static void main(String[] args) { Test test = new Test(); try { test.testTryCatch(); } catch (Exception e) { System.out.println("exception"); // 3 } } // 測試try/finally語句塊拋出異常的執(zhí)行順序 private void testTryCatch() throws Exception { try { System.out.println("try"); // 1 throw new Exception(); } finally { System.out.println("finally"); // 2 } } // 輸出: try finally exception 也就是說,先執(zhí)行try(// 1),然后執(zhí)行finally(// 2),然后執(zhí)行拋出的異常(// 3) 例5: public static void main(String[] args) { Test test = new Test(); try { test.testTryCatch(); } catch (IOException e) { System.out.println("exception"); // 4 } } // 測試catch中又拋出異常,其執(zhí)行順序 private void testTryCatch() throws IOException { try { System.out.println("try"); // 1 throw new Exception(); } catch (Exception e) { System.out.println("catch before throw new exception"); // 2 throw new IOException(); // System.out.println("catch after throw IOException"); // 無法到達的代碼 } finally { System.out.println("finally"); // 3 } } 輸出: try catch before throw new exception finally exception 也就是說,先執(zhí)行try(//1),再執(zhí)行catch(//2),然后finally(//3),最后外部的catch(//4)。 |
|