Java – stackoverflowerror when calling recursively

The problem is a strict theory, but I can't find the answer Consider this short procedure:

public class SBtst {

    int i = 0;

    public static void main(String[] args) {
        new SBtst().rec();
    }

    public void rec() {
        System.out.println("rec is called "+i++);
        try {
            rec();
        } catch (StackOverflowError soe) {
            System.out.println("completed "+soe.getStackTrace().length);
        }
    }

}

After execution, I get output similar to:

rec is called 10472
rec is called 10473
rec is called 10474Recursion completed 1024

The question is:

>Why didn't println () complete the new line? It is understood that when the next rec () call is executed, an error should be thrown, and the println () after completion > why is there only 1024 elements in the stacktrace array, but it is equal to 10474? Does this mean that not every call is in the stack trace?

Solution

Why are exceptions apparently thrown out of println?

Your understanding is not quite correct At some point, the stack looks like:

…
rec()
  rec()
    rec()
      println()

Println also consumes resources (see matting ly 890's answer). There's no reason why you can't reach the limit at this point

Why does the stack trace contain fewer frames than actually used?

Look at the documentation for getstacktrace():

In Peter Lawley found the documentation, the stack size mentioned 1024 default limits:

There may be other factors at work For example, these questions refer to two other options:

> how to expand size of Java stack trace to see bottom of stack? (triggering a stack overflow)(-XXMaxJavaStackTraceDepth) > How to avoid the 1024 lines of Java exception stack limit(-Xss)

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>