首先大家来分析以下三个程序:
package test;
public class Test {
public static void main(String [] args){
System.out.println(Test.test());
}
static int test(){
int x=1;
try
{
return x;
}
finally
{
++x;
}
}
}
输出结果为:1
package test;
public class Test {
public static void main(String [] args){
Test t = new Test();
int b = t.test();
System.out.println(b);
}
public int test(){
try
{
return 1;
}
finally
{
return 2;
}
}
}
输出结果为:2
package test;
public class Test {
public static void main(String [] args){
Test tt = new Test();
System.out.println(tt.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;
}
}
输出结果为:
func1
func2
2
通过分析以上程序的结果,我们可以发现其执行顺序为,首先执行try语句里边的return,然后执行finally里边的语句,最后返回到调用语句。可以这样来理解,try语句首先返回值给调用语句,将其存放在调用语句,(当执行完finally语句后这个值是可能会变的),然后回来执行finally语句,当执行完finally之后再回去执行调用语句。