Infinite loop breaks method signature without compilation error [duplicate]
Solution 1:
The final }
of the method is unreachable - you only get a compilation error if it's possible to get to the end of the method without returning a value.
This is more useful for cases where the end of the method is unreachable due to an exception, e.g.
private String find(int minLength) {
for (String string : strings) {
if (string.length() >= minLength) {
return string;
}
}
throw new SomeExceptionIndicatingTheProblem("...");
}
The rule for this is in the JLS section 8.4.7:
If a method is declared to have a return type (§8.4.5), then a compile-time error occurs if the body of the method can complete normally (§14.1).
Your method can't complete normally, hence there's no error. Importantly, it's not just that it can't complete normally, but the specification recognizes that it can't complete normally. From JLS 14.21:
A
while
statement can complete normally iff at least one of the following is true:
- The
while
statement is reachable and the condition expression is not a constant expression (§15.28) with valuetrue
.- There is a reachable
break
statement that exits thewhile
statement.
In your case, the condition expression is a constant with value true
, and there aren't any break
statements (reachable or otherwise) so the while
statement can't complete normally.
Solution 2:
private String withoutReturnStatement() {
while(true) {
// you will never come out from this loop
} // so there will be no return value needed
// never reach here ===> compiler not expecting a return value
}
To more clarification try this
private String withoutReturnStatement() {
while(true) {}
return ""; // unreachable
}
It says unreachable
statement