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

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© lts0616 中级黑马   /  2015-12-30 19:54  /  453 人查看  /  1 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

public class Demo_Finally {
        public static void main(String[] args) {
         foo(1); //输出结果是?
                 foo(2); //输出结果是?
                System.out.println(output);
        }
       
        public static String output = "";
       
        public static void foo(int i){
                try {
                        if (i == 1) {
                                throw new Exception();
                        }
                        output += "1";
                } catch (Exception e) {
                        output += "2";
                        return;
                } finally {
                        output += "3";
                }
               
                output += "4";
        }
求分析?看不懂

1 个回复

倒序浏览
foo(1); output变成了23        
i == 1 成立, 抛出异常, 直接catch住, 不走output +="1";
output += "2";                       //output变成"2"
return;                                  //建立了返回通道, 检查发现有finally需要执行, 所以还没有跳出
finally { output += "3"; }         //output变成"23"  finally执行结束, 方法结束. 没有执行到  output += "4";

foo(2);
i != 1;                                                        // throw new Exception(); 不执行
output += "1";                                            // output变成 "231"  
catch (Exception e) { output += "2";}             //程序没出错  不走catch
finally {  output += "3"; }                              // output变成 "2313"
output += "4";                                             //output变成 "23134"   方法结束
System.out.println(output);                            //23134
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马