黑马程序员技术交流社区

标题: 关于执行顺序的问题? [打印本页]

作者: ㄨ____陌生    时间: 2013-4-4 23:47
标题: 关于执行顺序的问题?
本帖最后由 ㄨ____陌生 于 2013-4-5 15:20 编辑

try {}里有一个return语句,那么紧跟在这个try后的finally {}里的code会不会被执行,什么时候被执行,在return前还是后?


public  class Test {

    public static void main(String[] args) {
      System.out.println(new Test().test());;
    }

    static int test()
    {
       int x = 1;
       try
       {
           return x;
       }
       finally
       {
           ++x;
       }
    }

}

---------执行结果 ---------
1

运行结果是1,为什么呢?

作者: 刘印12    时间: 2013-4-4 23:52
finaliy 是一定要执行的代码,除非System.exit推出系统  他是在return后执行的,在以后IO中用到finaliy的时候比较多
作者: zjm10zj    时间: 2013-4-5 00:05
按照流程顺序,finally是在try后执行的,即在return后执行的,当执行到return x时就返回调用主函数了!后面的就不会被执行到了
作者: 王川    时间: 2013-4-5 00:13
  1. public class Test {
  2.         public static void main(String[] args) {
  3.                 System.out.println(new Test().test());
  4.         }
  5.        
  6.         static int test()
  7.             {
  8.                int x = 1;
  9.                try
  10.                {
  11.                        System.out.println(x);//打印1
  12.                    return x;
  13.                }
  14.                finally
  15.                {
  16.                    ++x;
  17.                    System.out.println(x);//打印2
  18.                }
  19.             }
  20. }
复制代码
通过调试,首先执行try中的语句,然后执行finally中的,finally中的x还是++了的。但是return的x已经记下了刚才的1,所以最终返回的是1
作者: 炉海佳    时间: 2013-4-5 00:13
本帖最后由 炉海佳 于 2013-4-5 00:15 编辑

为什么是1,因为没有发生异常,因为返回的是1,后面的++x本来是2的没有返回,也就返回了1,finally肯定会执行,而且是try之后执行,你在++x;之后加上一句打印语句就知道了
  1. class Test {

  2.     public static void main(String[] args) {
  3.       

  4.    System.out.println(new Test().test());
  5.       
  6.     }
  7.     static int test()
  8.     {int x = 1;
  9.       
  10.        try
  11.        {
  12.            return x;
  13.          
  14.        }
  15.        finally
  16.        {
  17.            ++x;
  18.      System.out.println("x1:"+x);//这里打印的结果是x1:2
  19.        }
  20.       
  21.    
  22.     }
  23.    
  24. }
复制代码

作者: 田光峰    时间: 2013-4-5 15:13
public  class Test {

    public static void main(String[] args) {
      System.out.println(new Test().test());;
    }
    static int test()
    {
       int x = 1;
       try
       {
           return x;
       }
       finally
       {
           ++x;
       }
    }
   
}

是先执行try再执行finally,finally表示的是一定要执行的代码,当try中有return时再返回前要看看有没有finally
如果有要执行finally,而返回的值还是return中应该返回的值。




欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2