//清单一: public class Test1 { public static void main(String[] args) { System.out.println("return value of test(): " + test()); } public static int test() { int i = 1; // if(i == 1) // return 0; System.out.println("the previous statement of try block"); i = i / 0; try { System.out.println("try block"); return i; } finally { System.out.println("finally block"); } } } //结论:如果在try中遇到异常,如果没有catch,则直接退出,不会执行finally /*执行结果:the previous statement of try block Exception in thread "main" java.lang.ArithmeticException: / by zero at com.testfinally.sym.Test1.test(Test1.java:12) at com.testfinally.sym.Test1.main(Test1.java:5) */ //清单二: public class Test2 {
public static void main(String[] args) { System.out.println("return value of test(): " + test()); }
public static int test() { int i = 1; try { System.out.println("try block"); System.exit(0); return i; } finally { System.out.println("finally block"); } } } //结论同上 /*执行结果:try block*/
//清单三: public class Test3 { public static void main(String[] args) { try { System.out.println("try block"); return; } finally { System.out.println("finally block"); } } } //结论:正常情况下,finally先于return执行 /*执行结果:try block finally block*/
//清单四: public class Test4 { public static void main(String[] args) { System.out.println("reture value of test() : " + test()); }
public static int test() { int i = 1; try { System.out.println("try block"); i = 1 / 0; return 1; } catch (Exception e) { System.out.println("exception block"); return 2; } finally { System.out.println("finally block"); } } } //结论:当在try中出现异常,则进入catch;这种情况下三个块中return的优先级:如果、//finally中有return,则函数的返回值就为此return的值;如果finally中没有return,而//catch中有return,则最后的返回值就采用此return的值;如果finally中没有//return,catch中也没有return,则最后的返回值就采用try中的return的值。如果在执行//的时候不需要进入到catch,则不用关注catch中的return值 /*执行结果:try block exception block finally block reture value of test() : 2*/
//清单五: public class Test5 {
public static void main(String[] args) { System.out.println("return value of getValue(): " + getValue()); } public static int getValue() { try { return 0; } finally { return 1; } } } //结论同上 /*执行结果:return value of getValue(): 1*/
//清单6: public class Test6 {
public static void main(String[] args) {
System.out.println("return value of getValue(): " + getValue()); }
System.out.println("return value of getValue(): " + getValue()); }
public static int getValue() { int i = 1; try { i = 4; } finally { i++; return i; } } } //结论:return在finally中,情况与清单6就不一样了,属于正常返回 /*执行结果:return value of getValue(): 5*/
//清单8 public class Test8 {
public static void main(String[] args) {
System.out.println("return value of getValue(): " + getValue()); }
public static int getValue() { int i = 1; try { i = 4; } finally { i++; } return i; } } //结论:return在外面也是正常返回 /*执行结果:return value of getValue(): 5*/