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));
}
}
|