执行如下代码环,其递归循环次数将达到3^N次(N为最大栈深)为天文数字因此几乎无限循环
public static void foo() {
try {
System.out.println("try");
foo();
} catch (Throwable e) {
System.out.println("catch");
foo();
} finally {
System.out.println("finally");
foo();
}
}
上面代码控制台打印内容如下,我好奇的为什么没有输出“catch”,将上述的catch (Throwable e) 换成catch (StackOverflowError e)后正常输出“catch”
···
try
try
try
try
try
try
fifinallyfinallyfinally
tryfinallyfinally
try
tryfinallyfinally
tryfinallyfinally
try
try
···
我尝试去统计try/catch/finally块的执行次数,编写如下代码,创建一个线程每隔3秒钟输出统计结果
static Counter counter = new Counter();
public static void main(String[] args) {
new Thread(() -> {
try {
for (; ; ) {
TimeUnit.SECONDS.sleep(3);
System.out.println(counter);
}
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}).start();
foo();
}
static void foo() {
try {
counter.t++;
System.out.println("try");
foo();
} catch (Throwable e) {
counter.c++;
System.out.println("catch");
foo();
} finally {
counter.f++;
System.out.println("finally");
foo();
}
}
static class Counter {
int t, c, f;
@Override
public String toString() {
return "Counter{" +
"t=" + t +
", c=" + c +
", f=" + f +
'}';
}
}
结果控制台输出如下结果,可以看到try、catch、finally块的执行次数基本相同(try块初始化递归时多了一个最大栈深的次数)
try
try
trycatcatchfinallycatchfinallycatchfinally
trycatchfinally
trycatchfinallycatch
try
···
···
trycatchfinallyCounter{t=17028, c=10621, f=10615}
可是当我将创建输出统计结果的线程的代码注释掉后“catch”又不输出了,甚至当我仅仅创建该线程不去start()时却可以输出“catch”,有谁知道这个“catch”什么情况下输出吗?