The following example is from Khalid book with little modification.
My question is if we comment out line3 like above, then we have a compiler error: C:\WINDOWS\Desktop\pgjc-source\Example_8.6\ExceptionsInInstBlocks.java:14: initializer must be able to complete normally { // Instance initializer block The compiler said "initializer must be able to complete normally". This is obviously not true( just compile with line 3 and see what happens). I just find it interesting the if(true) line make such difference when compiling. Another question: Khalid said: "Instance initializer blocks in anonymous classe can throw any exceptions". But I have trouble compiling the following code (also from his book with little modification):
I found nowhere to declare the caught exception. The only way out is use try and catch block. Then the exception handling in instance initializer in this case will be the same as in a static intializer. Why Khalid said the former has greater freedom?
Just giving a shot at this one, not sure if it makes enough sense. I think, you need to connect lot of things together here. From JLS 8.6: "It is a compile-time error if an instance initializer cannot complete normally " From JLS: 14.20 "A break, continue, return, or throw statement cannot complete normally"
Hence the following code will give a compiler error ('initializer must be able to complete normally') . class Test{ { throw new TestException(); } } class TextException extends RuntimeException{ }
Also from JLS 14:20, "HYPOTHETICAL: An if-then statement can complete normally iff at least one of the following is true: The if-then statement is reachable and the condition expression is not a constant expression whose value is true. The then-statement can complete normally " So, the following code compiles fine as, if-then statement is considered to complete normally (since if statement is reachable) and hence the instance initializer itself is considered to complete normally. class Test{ { if(true) // or if(false) throw new TestException(); } } class TextException extends RuntimeException{ }