Reputation: 3728
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.
Upvotes: 1
Views: 338
Reputation: 420971
[...] as far as I can see there is no code path that will get to that point? What am I missing?
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.
Upvotes: 2
Reputation: 2121
Even though it seems obvious that logAndTrowSpecificException
always throws an exception, the compiler can't know that for certain. It is possible to instrument the class at load time and replace the implementation of the method with one that does not (always) throw an exception.
Keyword: aspect oriented programming.
Upvotes: 1
Reputation: 121971
I suspect it does not know for certain that logAndThrowSpecificException()
will always throw an exception, even though it has a very clear name as to its purpose, so it would be possible for the end of testException()
to be reached.
Upvotes: 6