Reputation: 10220
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");
}
}
}
Upvotes: 2
Views: 148
Reputation: 100249
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.
Upvotes: 4
Reputation: 16536
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;
Upvotes: 2
Reputation: 44841
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!
Upvotes: 4