任何调用try 或者catch中的return语句之前,都会先执行finally语句,当然前提是finally存在。如果finally中有return语句,那么程序就return了,所以finally中的return是一定会被return的,编译器把finally中的return实现为一个warning。
例一
package exercise;
/**
* 基本类型测试try,finally
* @author Administrator
*
*/
public class TestReturnAndFinally {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println(new TestReturnAndFinally().test());;
}
static int test() {
int x = 1;
try {
return x;
}
finally {
++x;
}
}
}
结果:
1
例二
package exercise;
/**
* 引用类型测试try,finally
* @author Administrator
*
*/
public class TestReturnAndFinally3 {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println(new TestReturnAndFinally3().test());;
}
static StringBuffer test() {
StringBuffer a = new StringBuffer("init");
try {
a.append(" try");
return a;
}
finally {
a.append(" finally");
}
}
}
结果:
init try finally
例三
package exercise;
/**
* 普通类
* @author Administrator
*
*/
public class Quote {
public int a = 1;
}
package exercise;
/**
* 引用类型中的基本类型测试try,finally
* @author Administrator
*
*/
public class TestReturnAndFinally2 {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println(new TestReturnAndFinally2().test().a);;
}
static Quote test() {
Quote q = new Quote();
try {
return q;
}
finally {
q.a++;
}
}
}
结果:
2