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

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 杜成龙 中级黑马   /  2013-6-1 10:22  /  1504 人查看  /  5 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

本帖最后由 杜成龙 于 2013-6-12 19:05 编辑
  1. class Verification
  2. {
  3.        public static String output="";
  4.        public static void foo(int i)
  5.       {
  6.              try
  7.              {
  8.                    if(i==1)
  9.                    throw new Exception();
  10.                    output+="1";
  11.              }
  12.             catch (Exception e)
  13.             {
  14.                    output+="2";
  15.                    return;
  16.             }
  17.            finally
  18.           {
  19.                   output+="3";
  20.           }
  21.           output+="4";
  22.     }
  23.    public static void main(String[] args)
  24.    {
  25.           foo(0);
  26.           System.out.println(output);
  27.           foo(1);
  28.           System.out.println(output);

  29.    }
  30. }
复制代码
当调用foo(1)时,往里面传的是1,那么就会 throw new Exception(); 但是它下面还有语句,按说编译不应该是失败的吗,它怎么会通过呢?

评分

参与人数 1技术分 +1 收起 理由
袁梦希 + 1 很给力!

查看全部评分

5 个回复

倒序浏览
编译器是看下面的语句有没有机会执行到,想这种传值的方式是有机会执行到的,所以不会报错。报错是报那些一定不会执行到的语句。
回复 使用道具 举报
本帖最后由 刘海芳 于 2013-6-1 16:02 编辑

代码注释处给出了我的理解:
  1. class Verification
  2. {
  3.        public static String output="";
  4.        public static void foo(int i)
  5.       {
  6.              try
  7.              {
  8.                    if(i==1)
  9.                    throw new Exception();//这异常其实已经抛出去了,只是你使用了catch语句捕获了以此,当么用打印以此
  10.                    output+="1";//这句话没用放在这编译器不会报错,哪不会被执行
  11.              }
  12.             catch (Exception e)
  13.             {
  14.                     e.printStackTrace();//如果加上这句,你会发现编译已经报错了
  15.                    output+="2";
  16.                    return;
  17.             }
  18.            finally
  19.           {
  20.                   output+="3";
  21.           }
  22.           output+="4";
  23.     }
  24.    public static void main(String[] args)
  25.    {
  26.           foo(0);
  27.           System.out.println(output);
  28.           foo(1);
  29.           System.out.println(output);

  30.    }
  31. }
复制代码

评分

参与人数 1技术分 +1 收起 理由
殇_心。 + 1

查看全部评分

回复 使用道具 举报
哥们咋这么蛋疼呢。。。。。。。。。。。。。。
  1. public static void foo(int i)
复制代码
你本来想返回的数据是 String
起码就的这样写
  1. public static String foo(int i)
复制代码
而且还有

这个你看看。。。。。。你啥玩意都没有返回。。。。。。。。。。。。。。。。我真是服了哥们。。。。。。。。。。。。。。。。

评分

参与人数 1技术分 +1 收起 理由
殇_心。 + 1

查看全部评分

回复 使用道具 举报
编译检测语法格式正确与否,虽然在运行中跳过了,但是书写格式上是正确的。
回复 使用道具 举报
编译检测语法格式正确与否,虽然在运行中跳过了,但是书写格式上是正确的。
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马