In the first compiler, Case already knows that the instance initializer will never FileNotFoundException normally, because you explicitly selected FileNotFoundException there. You can say this is a smart compiler code evaluation. But if you make the compiler believe that the instance initializer has at least the slightest chance of shutting down, then the compiler will not complain at compile time. For example, in the code below, although the IDonotexist.txt file IDonotexist.txt not exist in my directory, and I'm sure it will throw a FileNotFoundException , but still the compiler will let it compile it successfully. Why? Since the presence of the file is checked at runtime, not at compile time.
class A { { FileReader fr = new FileReader(new File("IDonotexist.txt")); } public A() throws IOException {
This is similar to the case of initializing a final variable. For example, in the following code, the compiler will show a compile-time error
public void calling() { final int i; int k = 90; if ( k == 90) { i = 56; } System.out.println(i);
But if I replaced the condition if ( k == 90) with if(true) , then the compiler will not show an error. Since the compiler now knows that i will definitely be assigned some value.
Vishal k
source share