public class TestFinally {
public static void main(String args[]){
System.out.println(new TestFinally().test());
}
static int test(){
int x=1;
try{
return x;
}finally{
++x;
}
}
}
public class TestFinally1 {
public static void main(String args[]){
TestFinally1 t=new TestFinally1();
int b=t.get();
System.out.println(b);
}
public int get(){
try{
return 1;
}
finally{
return 2;
}
}
}
try中的return语句调用函数先于finally中调用的函数执行,也就说return语句先执行,finally语句后执行。Return并不是让函数马上返回,而是return语句执行后,将把返回结果放置进函数栈中,此时函数并不是马上返回,他要执行finally语句后才真正开始返回
public class FinallyTest2 {
public static void main(String args[]){
System.out.println(new FinallyTest2().test());
}
int test(){
try{
return func1();
}
finally{
return func2();
}
}
int func1(){
System.out.println("func1");
return 1;
}
int func2(){
System.out.println("func2");
return 2;
}
}
结论:finally中的代码比return和break语句后执行