StackOverflowError 什么时候发生? [英] When does StackOverflowError occur?

查看:27
本文介绍了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

我的查询是?

  1. 在 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.

这篇关于StackOverflowError 什么时候发生?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆