非 void 方法编译中缺少 return 语句
我遇到了一种情况,即非 void 方法缺少 return 语句,代码仍在编译。我知道 while 循环之后的语句是无法访问的(死代码),永远不会被执行。但是为什么编译器甚至没有警告返回某些内容呢?或者为什么一种语言会允许我们有一个非空洞的方法,它有一个无限循环而不返回任何东西?
public int doNotReturnAnything() {
while(true) {
//do something
}
//no return statement
}
如果我在 while 循环中添加一个 break 语句(甚至是条件语句),编译器会抱怨臭名昭著的错误:在 Eclipse 和 Visual Studio 中。Method does not return a value
Not all code paths return a value
public int doNotReturnAnything() {
while(true) {
if(mustReturn) break;
//do something
}
//no return statement
}
Java和C#都是如此。