try-catch 语句中的递归调用 [英] Recursive call in the try-catch statement
问题描述
我有以下代码片段:
public static void main(String[] args) {
foo();
}
public static void foo() {
try {
foo();
} catch (Throwable t) {
foo();
}
}
谁能解释一下这里发生了什么?请详细说明.
Can anyone explain me what's going on here? In details, please.
我已经更改了这部分并添加了 println
方法来显示某些内容:
I have changed this piece and added println
methods to show something:
...
try {
System.out.println("+");
foo();
} catch (Throwable t) {
System.out.println("-");
foo();
}
...
我得到了这样的东西(这个过程还没有停止):
I'm getting something like this (the process hasn't stopped):
+
+
+
+
+--
+--
+
+--
+--
+
+
+--
+--
+
+--
+--
+
+
+
+--
+--
推荐答案
foo
退出的唯一方法是因为 stackoverflow.我们可以通过
The only way foo
can exit is because of stackoverflow. We can simulate the effect by
public static void foo(int i)
{
if(i>=N) return; // stack too deep
foo(i+1);
foo(i+1);
}
这对于最大堆栈深度来说是指数级的昂贵.
which is exponentially expensive w.r.t to the max stack depth.
在我的机器上,花费的时间大约是6ns * 2^N
On my machine, the time it takes is about 6ns * 2^N
最大堆栈深度超过 10,000,因此需要大约
The max stack depth is over 10,000, so it will take about
10000000000000000000000000000000
....
(thousands of zeros)
...
00000000000000000000000000000000
完成该计划的年数,给予或接受一个常数因素:)
years to finish the program, give or take a constant factor:)
这篇关于try-catch 语句中的递归调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!