Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does the Java compiler allow exceptions to be listed in the throws section that it is impossible for the method to throw

The Java compiler seems inconsistent if there is some code that clearly can not throw an exception, and you write surrounding code that declares that the code can throw that exception.

Consider these code snippets.

Snippet 1

A catch of an exception that is never thrown.

public void g(){
        try {

        } catch (FileNotFoundException e) {//any checked exception

        }

}

It is compile error with message

Unreachable catch block for FileNotFoundException. This exception is never thrown from the try statement body

Snippet2

A throws declaration indicating an exception that is never thrown.

public void g() throws FileNotFoundException{
}

It compiles fine.

Therefore, the results of the first code snippet shows that the compiler can calculate if a method can throw an exception listed in the throws list. So it seems the compiler is deliberately not reporting an error for the second snippet. But Why? Why does the compiler allow you to write exceptions in throws section even if it the compiler knows thst those exceptions can not be thrown?

like image 311
gstackoverflow Avatar asked Mar 24 '14 13:03

gstackoverflow


1 Answers

The compiler allows this because the throws clause of the method is part of the signature of the method, rather than part of its implementation. It is possible that the implementation might change at some point, while keeping the signature the same. An old implementation might have thrown a checked exception, but the new one might not. Or the designer of the signature might have wanted to give the implementer the flexibility to throw a checked exception when that is not always necessary.

like image 123
Raedwald Avatar answered Sep 28 '22 00:09

Raedwald