Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checked exception and initializer block

Tags:

java

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?

like image 951
Salil Misra Avatar asked Feb 23 '13 15:02

Salil Misra


1 Answers

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.

like image 51
Bhesh Gurung Avatar answered Sep 24 '22 10:09

Bhesh Gurung