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

查看:72
本文介绍了什么时候发生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天全站免登陆