Search code examples
javaexceptionconstructorunchecked-exception

Facing java.lang.StackOverflowError on throwing unchecked exception from constructor


I was trying out to run the below code sample but getting StackOverflow error. It seems to stuck up in the infinite loop. Can anybody help me out in knowing what's going on in here?

Please find below code snippet

public class ConstructorExample {

    private ConstructorExample c1 = new ConstructorExample();

    public ConstructorExample(){
        throw new RuntimeException();
    }

    public static void main(String[] str){
        ConstructorExample c = new ConstructorExample();
    }
}

Solution

  • You have the member private ConstructorExample c1 = new ConstructorExample(); in the ConstructorExample class.

    When you instantiate a first instance of ConstructorExample, the JVM allocates memory for that ConstructorExample, then tries to instantiate the first member, c1. This instantiation starts with allocating memory for another ConstructorExample instance, and so on.

    Also, the runtime exception is irrelevant because the member initializer is executed before the constructor.