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

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 贾波 中级黑马   /  2013-11-30 13:18  /  1351 人查看  /  1 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

  1. public class Test {

  2.         private static int count = 0;

  3.         static {
  4.                 count++;
  5.         }

  6.         public Test() {
  7.                 System.out.println(count);
  8.                 count++;
  9.         }

  10.         private void throwException() throws Exception {
  11.                 throw new Exception();
  12.         }

  13.         public int getCount(boolean isThrow) {
  14.                 try {
  15.                         if (isThrow)
  16.                                 throwException();
  17.                         return (--count);
  18.                 } catch (Exception e) {
  19.                         System.out.println(count++);
  20.                 } finally {
  21.                         System.out.println(++count);
  22.                 }
  23.                 return ++count;
  24.         }

  25.         public static void main(String[] args) {
  26.                 Test test = new Test();
  27.                 System.out.println(test.getCount(false));
  28.                 System.out.println(test.getCount(true));
  29.         }

  30. }
复制代码
输出结果:
1
2
1
2
4
5


评分

参与人数 1技术分 +1 收起 理由
狼王 + 1 赞一个!继续努力哈。。。

查看全部评分

1 个回复

倒序浏览
public class Test {

        private static int count = 0;

        static {
                count++;
        }

        public Test() {
                System.out.println(count);
                count++;
        }

        private void throwException() throws Exception {
                throw new Exception();
        }

        public int getCount(boolean isThrow) {
                try {
                        if (isThrow)
                                throwException();
                        return (--count);
                } catch (Exception e) {
                        System.out.println(count++);
                } finally {
                        System.out.println(++count);
                }
                return ++count;
        }

        public static void main(String[] args) {
                                //从mian方法入手,首先加载静态代码块,count++,此时count=1,然后执行构造函数,打印1,count自增,count=2;
                Test test = new Test();
                                //下面调用getCount方法.传入false, 在try中--count,return语句已经记录下返回值为1 此时count=1.紧接着执行finally语句,打印2
                                //返回1,打印1,此时count为2
                System.out.println(test.getCount(false));
                                //调用getCount方法,抛出异常,进入catch语句,打印2,结束后count=3,继续执行finally语句,打印4,结束后count=4,最后return 5
                                //count = 5,打印5
                System.out.println(test.getCount(true));
        }

}

评分

参与人数 1技术分 +1 收起 理由
狼王 + 1 赞一个!不错哦,谢谢你的回答。。。。.

查看全部评分

回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马