finally語句必定是會被執行的,無論前邊的try塊catch塊中有無return語句,而且若是finally中存在return語句,這個return語句將會是最後執行的return語句,即函數最後的返回值。try,catch中的return並非讓函數直接返回,而是return語句執行完畢,把返回結果放到函數棧中,轉而執行finally塊,因此,如果finally中含有return語句,那麼函數棧中的返回值將被刷新。看如下幾種狀況:java
1:try有return,finally無函數
public class TryFinallyReturnTest { static int test(){ int x=1; try { ++x; return x; } catch (Exception e) { // TODO: handle exception }finally{ ++x; System.out.println("finally++x"+x); } return 0; } public static void main(String[] args) { System.out.println(new TryFinallyReturnTest().test()); } }
輸出結果:this
finally++x3 2
2:當 try 中拋出異常且 catch 中有 return 語句, finally 中沒有 return 語句, java 先執行 catch 中非 return 語句,再執行 finally 語句,最後執行 catch 中 return 語句。spa
public class Test { public int testTry(){ FileInputStream fi=null; try{ fi=new FileInputStream(""); }catch(FileNotFoundException fnfe){ System.out.println("this is FileNotFoundException"); return 1; }catch(SecurityException se){ System.out.println("this is SecurityException"); }finally{ System.out.println("this is finally"); } return 0; } public static void main(String[] args) { Test t= new Test(); System. out .println(t.testTry()); } } Output : this is FileNotFoundException this is finally 1
3:當 try 中拋出異常且 catch 中有 return 語句, finally 中也有 return 語句, java 先執行 catch 中非 return 語句,再執行 finally 中非 return 語句,最後執行 finally 中 return 語句,函數返回值爲 finally 中返回的值。.net
public class Test { public int testTry(){ FileInputStream fi=null; try{ fi=new FileInputStream(""); }catch(FileNotFoundException fnfe){ System.out.println("this is FileNotFoundException"); return 1; }catch(SecurityException se){ System.out.println("this is SecurityException"); }finally{ System.out.println("this is finally"); return 3; } //return 0; } public static void main(String[] args) { Test t= new Test(); System. out .println(t.testTry()); } } Output : this is FileNotFoundException this is finally 3
4:另外,throw語句以後不能接任何語句,unreachable。blog
部分摘自http://blog.csdn.net/leigt3/archive/2010/01/15/5193091.aspxget