public  class TryCatchReturn { /**
 * @param args add by zxx ,Dec 9, 2008
 */
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println(new TryCatchReturn().test());;
}
static int test()
{
int x = 1;
try
{
return x;
}
finally
{
++x;
}
}
}
这个程序的运行结果是1,是不是程序是在try里已经保存了x,然后运行finally,但是最后依然按原来保存的1返回public  class TryCatchReturn3 { /**
 * @param args add by zxx ,Dec 9, 2008
 */
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println(new TryCatchReturn3().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
最后是2而不是1,这是为什么?

解决方案 »

  1.   

       按一般传统的理解是先执行try,然后再执行finally,但如果在try中遇到有return 语句,则会将该语句保存起来,转而先去执行finally内的语句,类似于调用一个子程序一样,当finally执行完后再回过头来执行try中的返回语句,但是如果在finally中遇到return 语句时则直接返回了,此时try中的return 是不被执行的。
      
      
     
      

  2.   

    这个也成为月经贴了
    javap -c TryCatchReturn 一目了然,毋庸多言