A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 如梭的日月 中级黑马   /  2014-11-25 07:24  /  1049 人查看  /  6 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

用代码证明,在try中写了return,后面又写了finally,是先执行return还是先执行finally?

评分

参与人数 1技术分 +1 收起 理由
杨佳名 + 1

查看全部评分

6 个回复

倒序浏览
先finally,后return,return完会结束函数
回复 使用道具 举报
41try {}里有一个return语句,那么紧跟在这个try后的finally {}里的code会不会被执行,什么时候被执行,在return前还是后?
      也许你的答案是在return之前,但往更细地说,我的答案是在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,为什么呢?主函数调用子函数并得到结果的过程,好比主函数准备一个空罐子,当子函数要返回结果时,先把结果放在罐子里,然后再将程序逻辑返回到主函数。所谓返回,就是子函数说,我不运行了,你主函数继续运行吧,这没什么结果可言,结果是在说这话之前放进罐子里的。
42、下面的程序代码输出的结果是多少?
public class  smallT
{
      public static void  main(String args[])
      {
            smallT t  = new  smallT();
            int  b  =  t.get();
            System.out.println(b);
      }
      
      public int  get()
      {
            try
            {
                  return 1 ;
            }
            finally
            {
                  return 2 ;
            }
      }
}

返回的结果是2。
我可以通过下面一个例子程序来帮助我解释这个答案,从下面例子的运行结果中可以发现,try中的return语句调用的函数先于finally中调用的函数执行,也就是说return语句先执行,finally语句后执行,所以,返回的结果是2。Return并不是让函数马上返回,而是return语句执行后,将把返回结果放置进函数栈中,此时函数并不是马上返回,它要执行finally语句后才真正开始返回。
在讲解答案时可以用下面的程序来帮助分析:
public  class Test {
     /**
      * @param args add by zxx ,Dec 9, 2008
      */
     public static void main(String[] args) {
          // TODO Auto-generated method stub
          System.out.println(new Test().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
结论:finally中的代码比return 和break语句后执行

评分

参与人数 1技术分 +3 收起 理由
杨佳名 + 3 刚想展示下实力,结果回答了!

查看全部评分

回复 使用道具 举报 1 0
  1. class T1
  2. {
  3.   public static void main(String[] args)
  4.   {
  5.           try
  6.           {
  7.                   System.out.println("try !");
  8.                   return;   //先执行return,否则执行finally后 下面语句会输出,
  9.           }
  10.           finally
  11.           {
  12.                   System.out.println("finally");
  13.           }         
  14.           //System.out.println("return");//因为先执行了return所以下面这句话无法访问
  15.   }
  16.   
  17. }
复制代码


回复 使用道具 举报
感谢大神解答,长知识了
回复 使用道具 举报
来学习代码的   大神给力
回复 使用道具 举报
啊,谢谢大神的解答,,涨姿势了。。。
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马