Understanding the Java stack

2020-02-17 05:31发布

There is this code:

public class Main {
    public static void main(final String[] args) throws Exception {
        System.out.print("1");
        doAnything();
        System.out.println("2");
    }

    private static void doAnything() {
        try {
            doAnything();
        } catch (final Error e) {
            System.out.print("y");
        }
    }
}

And there is the output:

1yyyyyyyy2

Why does it print "y" eight times and no more. How can Java call println() when StackOverflowError encountered?

7条回答
混吃等死
2楼-- · 2020-02-17 06:07

My bet is that by invoking print in the catch block you force another StackOverflowError that is caught by the outer block. Some of these calls will not have enough stack for actually writing the output stream.

The JLS says that:

Note that StackOverflowError, may be thrown synchronously by method invocation as well as asynchronously due to native method execution or Java virtual machine resource limitations.

The Java SE platform permits a small but bounded amount of execution to occur before an asynchronous exception is thrown.

The delay noted above is permitted to allow optimized code to detect and throw these exceptions at points where it is practical to handle them while obeying the semantics of the Java programming language. A simple implementation might poll for asynchronous exceptions at the point of each control transfer instruction. Since a program has a finite size, this provides a bound on the total delay in detecting an asynchronous exception.

查看更多
登录 后发表回答