try/catch/finally測(cè)試結(jié)論:
1、如果某個(gè)異常發(fā)生的時(shí)候沒(méi)有在任何地方捕獲它,程序就會(huì)終止執(zhí)行,并在控制臺(tái)上顯示異常信息 2、不管是否有異常被捕獲,finally子句中的代碼都會(huì)執(zhí)行 3、當(dāng)代碼拋出一個(gè)異常時(shí),就會(huì)終止對(duì)方法中剩余代碼的處理,并退出這個(gè)方法 4、finally后面的代碼被執(zhí)行的條件: a、代碼沒(méi)有拋出異常 或者b、代碼拋出異常被捕獲,而且捕獲的時(shí)候沒(méi)有再拋出異常 5、建議用try/catch和try/finally語(yǔ)句塊,前者是將異常攔截;而后者是為了將異常送出去,并執(zhí)行所需代碼 6、finally優(yōu)先于try中的return語(yǔ)句執(zhí)行,所以finally中,如果有return,則會(huì)直接返回,而不是調(diào)用try中的return;catch中的return也是一樣,也就是說(shuō),在return之前,肯定會(huì)先調(diào)用finally中的return 例1: // 測(cè)試捕獲異常后,再次拋出異常,不會(huì)執(zhí)行finally后面的語(yǔ)句// 1 // 因?yàn)榫幾g就通不過(guò),直接報(bào):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: // 測(cè)試異常被捕獲,會(huì)繼續(xù)執(zhí)行finally后面的語(yǔ)句// 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: // 測(cè)試finally中的return優(yōu)先級(jí)最高 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 } } // 測(cè)試try/finally語(yǔ)句塊拋出異常的執(zhí)行順序 private void testTryCatch() throws Exception { try { System.out.println("try"); // 1 throw new Exception(); } finally { System.out.println("finally"); // 2 } } // 輸出: try finally exception 也就是說(shuō),先執(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 } } // 測(cè)試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"); // 無(wú)法到達(dá)的代碼 } finally { System.out.println("finally"); // 3 } } 輸出: try catch before throw new exception finally exception 也就是說(shuō),先執(zhí)行try(//1),再執(zhí)行catch(//2),然后finally(//3),最后外部的catch(//4)。 |
|
|