Why doesn’t the following code compile:
@Test
public boolean testException() throws MyException {
try {
System.out.println("Try some resource, which may throw an exception");
return resource.getSomething();
} catch (Exception e) {
logAndThrowSpecificException(e);
} finally {
System.out.println("Clean up");
}
}
private void logAndThrowSpecificException(Exception e) throws MyException {
throw new MyException("Checked exception", e);
}
In IntelliJ it complains that I need to return a value from the last line of the testException() method, but as far as I can see there is no code path that will get to that point? What am I missing?
There are similar questions on StackOverflow, but the best resolution I could find was to just put in a return null statement. There was no proper answer to why this was necessary.
There is, in general, no way to tell if a certain path is possible or not (standard result, follows immediately from the halting problem).
Due to this, the compiler won’t put much effort into analyzing such things. In fact it won’t even bother looking outside the method currently being compiled, which is why you get the error in this case.
The specifics of what is regarded as reachable code is specified in the Java Language Specification in Section 14.21 Unreachable Statements. In fact, it would be a direct violation of the specification if a compiler compiled the code you provided.