1、不能在finally塊中執行return,continue等語句,否則會把異常“吃掉”;
2、在try,catch中假如有return語句,則在執行return之前先執行finally塊
請大家仔細看下面的例子:
| 以下是引用片段: public class TryTest { public static void main(String[] args) { try { System.out.PRintln(TryTest.test());// 返回結果為true其沒有任何異常 } catch (Exception e) { System.out.println("Exception from main"); e.printStackTrace(); } doThings(0); } public static boolean test() throws Exception { try { throw new Exception("Something error");// 第1步.拋出異常 } catch (Exception e) {// 第2步.捕捉的異常匹配(聲明類或其父類),進入控制塊 System.out.println("Exception from e");// 第3步.打印 return false;// 第5步. return前控制轉移到finally塊,執行完后再返回(這一步被吃掉了,不執行) } finally { return true; // 第4步. 控制轉移,直接返回,吃掉了異常 } } public static void doThings(int i) { try { if(i==0) { //在執行return之前會先執行finally return; } int t=100/i; System.out.println(t); }catch(Exception ex) { ex.printStackTrace(); } finally { System.out.println("finally"); } } } |
新聞熱點
疑難解答