为什么可以从StackOverflowError中恢复? [英] Why is it possible to recover from a StackOverflowError?

查看:400
本文介绍了为什么可以从StackOverflowError中恢复?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很惊讶即使在 之后仍然可以继续执行Java中发生了StackOverflowError

I'm surprised at how it is possible to continue execution even after a StackOverflowError has occurred in Java.

我知道 StackOverflowError 是类Error的子类。
类错误被称为Throwable的子类,表示合理的应用程序不应该试图捕获的严重问题。

I know that StackOverflowError is a sublass of the class Error. The class Error is decumented as "a subclass of Throwable that indicates serious problems that a reasonable application should not try to catch."

这听起来更像是一个推荐而不是一个规则,主张捕获像StackOverflowError这样的错误实际上是允许的,这取决于程序员不这样做的合理性。并且看,我测试了这段代码并且它正常终止。

This sounds more like a recommendation than a rule, subtending that catching a Error like a StackOverflowError is in fact permitted and it's up to the programmer's reasonability not to do so. And see, I tested this code and it terminates normally.

public class Test
{
    public static void main(String[] args)
    {
        try {
            foo();
        } catch (StackOverflowError e) {
            bar();
        }
        System.out.println("normal termination");
    }

    private static void foo() {
        System.out.println("foo");
        foo();
    }

    private static void bar() {
        System.out.println("bar");
    }
}

这怎么可能?我想当抛出StackOverflowError时,堆栈应该已经满了,以至于没有空间调用另一个函数。错误处理块是在另一个堆栈中运行,还是在这里发生了什么?

How can this be? I think by the time the StackOverflowError is thrown, the stack should be so full that there is no room for calling another function. Is the error handling block running in a different stack, or what is going on here?

推荐答案

当堆栈溢出且<$抛出c $ c> StackOverflowError ,通常的异常处理展开堆栈。展开堆栈意味着:

When the stack overflows and StackOverflowError is thrown, the usual exception handling unwinds the stack. Unwinding the stack means:


  • 中止当前活动函数的执行

  • 删除其堆栈框架,继续调用函数

  • 中止调用者的执行

  • 删除其堆栈帧,继续调用函数

  • 依此类推...

  • abort the execution of the currently active function
  • delete its stack frame, proceed with the calling function
  • abort the execution of the caller
  • delete its stack frame, proceed with the calling function
  • and so on...

...直到异常被捕获。这是正常的(实际上是必要的),并且与抛出的异常和原因无关。由于您在第一次调用 foo()之外捕获异常,因此数千个 foo 堆栈框架填满了堆栈已全部解开,大部分堆栈可以再次使用。

... until the exception is caught. This is normal (in fact, necessary) and independent of which exception is thrown and why. Since you catch the exception outside of the first call to foo(), the thousands of foo stack frames that filled the stack have all been unwound and most of the stack is free to be used again.

这篇关于为什么可以从StackOverflowError中恢复?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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