Java中的try/catch/finally
样例1:
1 public class Test{ 2 public static String output = ""; 3 public static void foo(int i){ 4 try{ 5 if(i == 1){ 6 throw new Exception(); 7 } 8 }catch(Exception e){ 9 output += "2"; 10 return ; 11 }finally{ 12 output += "3"; 13 } 14 output += "4"; 15 } 16 17 public static void main(String[] args){ 18 foo(0); 19 foo(1); 20 System.out.println(output); 21 } 22 }
输出:3423
说明:try之后并定执行finally,finally如果没有返回,则会继续执行下面的代码
样例2:
1 public class Test{ 2 public static String output = ""; 3 public static void foo(int i){ 4 try{ 5 if(i == 1){ 6 throw new Exception(); 7 } 8 }catch(Exception e){ 9 output += "2"; 10 }finally{ 11 output += "3"; 12 } 13 output += "4"; 14 } 15 16 public static void main(String[] args){ 17 foo(0); 18 foo(1); 19 System.out.println(output); 20 } 21 }
输出:34234