无限循环中断方法签名而没有编译错误 [英] Infinite loop breaks method signature without compilation error
问题描述
我想知道为什么Java中允许使用以下代码而不会出现编译错误?
在我看来,这段代码通过不返回任何 String
来中断方法签名。
有人可以解释我在这里缺少的东西吗?
I am wondering why is the following code allowed in Java, without getting compilation error?
In my opinion, this code breaks method signature by not returning any String
.
Could someone explain what I'm missing here?
public class Loop {
private String withoutReturnStatement() {
while(true) {}
}
public static void main(String[] a) {
new Loop().withoutReturnStatement();
}
}
推荐答案
该方法的最终}
无法访问 - 如果可以在不返回值的情况下到达方法的末尾,则只会出现编译错误。
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("...");
}
此规则在JLS第8.4.7节:
如果声明方法具有返回类型(第8.4.5节),则如果方法体可以正常完成(第14.1节),则会发生编译时错误。 / p>
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).
您的方法无法正常完成,因此没有错误。重要的是,它不仅仅是它无法正常完成,而且规范识别它无法正常完成。来自 JLS 14.21 :
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
而
语句可以正常完成iff至少满足下列条件之一:
A
while
statement can complete normally iff at least one of the following is true:
-
,而
语句可以访问且条件表达式不是具有值的常量表达式(第15.28节)true
。 - 有一个可到达的
break
语句退出while
声明。
- 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.
在您的情况下,条件表达式是一个值为 true
的常量,并且没有任何 break
语句(可到达或以其他方式)所以而
语句无法正常完成。
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.
这篇关于无限循环中断方法签名而没有编译错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!