StackOverflowError 什么时候发生?
根据 Oracle 的说法,一个 StackOverflowError是:
According to Oracle, a StackOverflowError is:
由于应用程序递归太深而发生堆栈溢出时引发.
Thrown when a stack overflow occurs because an application recurses too deeply.
我知道什么是递归,通常递归函数,如果没有正确终止,会导致 StackOverflowError.为了检查在抛出 StackOverflowError
之前发生的递归调用的数量,我编写了以下代码:
I know what recursion is and normally recursive functions, if not terminated properly, lead to StackOverflowError. To check the number of recursive calls that happen before StackOverflowError
is thrown, I wrote this code:
package ErrorCases;
public class StackOverFlowError {
static int i=0;
void a()
{
//System.out.println("called "+(++i));
try{
++i;
a();
}catch(Error e)
{
System.out.println(e.getClass());
System.out.println(i);
}
}
public static void main(String[] args) {
new StackOverFlowError().a();
}
}
i
的值给出了在 JVM 抛出 StackOverflowError 之前对 a()
的递归调用次数.i
的值在每次运行时都不同,例如:
the value of i
gives the count of recursive calls to a()
before JVM threw StackOverflowError.
The value of i
is different in every run like:
output 1: class java.lang.StackOverflowError
10466
Output 2: class java.lang.StackOverflowError
10470
我的查询是?
在 JVM 抛出之前,递归必须发生多深
StackOverflowError
?
我们能否在 StackOverflowError
发生后恢复被扔了?
Can we recover once a StackOverflowError
has
been thrown?
推荐答案
深度取决于两件事:
1:栈的大小.
2:每次递归使用的堆栈空间量.
2: The amount of stack space used in each recursion.
函数参数、局部变量和返回地址都在栈上分配,对象在堆上分配.
Function parameters, local variables and the return address are all allocated on the stack while objects are allocated on the heap.
恢复
有可能恢复.
try {
myDeepRecursion();
} catch (StackOverflowError e) {
// We are back from deep recursion. Stack should be ok again.
}
但是,请注意以下有关错误的信息(来自 java API 文档):
However, note the following regarding errors (from the java API doc):
错误是 Throwable 的子类,表示合理的应用程序不应尝试捕获的严重问题.
注意事项:虽然在递归函数中捕获异常是可以的,但不要试图捕获错误.如果堆栈已满,则错误处理将导致新的错误.简单的事情,例如对 System.out.println()
的调用将失败,因为堆栈上没有空间用于返回地址.
A note of caution: While catching exceptions inside a recursive function is ok, don't try to catch errors. If the stack is full, then the error handling will cause new errors. Simple things, such as a call to System.out.println()
will fail because there is no room left on the stack for the return address.
这就是为什么错误应该在递归函数之外被捕获.
That is why errors should be caught outside the recursive function.
相关文章