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.
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
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?
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.
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