According to JLS: it is a compile-time error if an instance variable initializer or instance initializer of a named class can throw a checked exception class, unless that exception class or one of its superclasses is explicitly declared in the throws clause of each constructor of its class and the class has at least one explicitly declared constructor.
So if I do this -
class A{
{
throw new FileNotFoundException();
}
public A() throws IOException{
// TODO Auto-generated constructor stub
}
}
This gives a compile time error "initializer must complete normally"
while
class A{
{
File f=new File("a");
FileOutputStream fo=new FileOutputStream(f);
fo.write(3);
}
public A() throws IOException{
// TODO Auto-generated constructor stub
}
}
This code doesn't show any compile time error. Why doesn't the previous code compile even if I have declared a throws clause in the constructor?
There should be some condition when the initializer can actually complete without any exception.
In your case there is no way that it can happen.
Try:
if(/*condition-to-fail*/) {
/*Not always, only when something is wrong. Compiler knows that.*/
throw new FileNotFoundException();
}
Update:
The following statement is actually throwing the exception.
throw new FileNotFoundException();
So with no condition your program execution always ends there.
While in the following -
FileOutputStream fo = new FileOutputStream(f);
the constructor FileOutputStream(File)
doesn't always throw that exception.
The throws clause in public FileOutputStream(File file) throws FileNotFoundException
is only saying that it might throw that exception, and it will do it only if at runtime the file is not found otherwise not.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With