Java Reference
In-Depth Information
< Day Day Up >
Puzzle 40: The Reluctant Constructor
Although it is common to see a throws clause on a method declaration, it is less common to see one
on a constructor declaration. The following program has such a declaration. What does it print?
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");
}
}
}
Solution 40: The Reluctant Constructor
The main method invokes the Reluctant constructor, which throws an exception. You might
expect the catch clause to catch this exception and print I told you so . A closer look at the
program reveals that the Reluctant instance contains a second internal instance, and its constructor
also throws an exception. Whichever exception gets thrown, it looks as though the catch clause in
 
 
Search WWH ::




Custom Search