2

The following program compiles correctly. What is causing the Stack Overflow Error? How is the exception pushed on to the stack?

public class Reluctant {

    private Reluctant internalInstance = new Reluctant();

    public Reluctant() throws Exception {
        throw new Exception("I’m not coming out");
    }

    public static void main(String[] args) {
        try {
            Reluctant b = new Reluctant();
            System.out.println("Surprise!");
        } catch (Exception ex) {
            System.out.println("I told you so");
        }
    }
}

3 Answers 3

4

You have a field initialization code which is automatically added to the constructor body by javac compiler. Effectively your constructor looks like this:

private Reluctant internalInstance;

public Reluctant() throws Exception {
    internalInstance = new Reluctant();
    throw new Exception("I’m not coming out");
}

So it calls itself recursively.

Sign up to request clarification or add additional context in comments.

3 Comments

just know this, your answer helps!
Didn't know the field initialization moves to constructor. So, if its the first becomes statement like you mentioned. The exception is never thrown. Thanks to recursion.
@Sorter: and if you have multiple constructors, the same field initialization code is added to every single constructor (just after superclass initialization, but before actual constructor body).
4

This line in your main method results in infinite recursion:

Reluctant b = new Reluctant();

Every time you try to create an instance of Reluctant, the first thing you do is create another instance, which creates another instance, which creates another instance, which... You get the idea.

Voila, stack overflow!

1 Comment

That's the line where the recursion starts.
2

You have an infinite loop. Every instance of Reluctant class instantiates another Reluctant object on internalInstance declaration. So, when you instantiate the first Reluctant object on your main method, the program creates one instance after another, over and over again, till the stack overflows.

Replace this line.-

private Reluctant internalInstance = new Reluctant();

for

private Reluctant internalInstance;

1 Comment

Well explained the recursion process.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.