Showing posts from July, 2020

Puzzle: The throws clause on a constructor declaration

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 Test { private Test instance = new Test() ; public Test () throws Exception { throw new Exception( "Runtime Exception" ) ; } public static void main (String[] args) { try { Test b = new Test() ; System. out .println( "Surprise!" ) ; } catch (Exception ex) { System. out .println( "Exception throw by constructor" ) ; } } } The main method invokes the constructor of Test class, which throws an exception. You might expect the catch clause to catch this exception and print "Exception throw by constructor". But if you tried running it, you found that it does not print anything : It throws a StackOverflowError . Why? if you have a closer look at the program the