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?