看下面这个Java中的无限while
循环。它会导致紧接着它下面的语句在编译时出现错误。
while(true) {
System.out.println("inside while");
}
System.out.println("while terminated"); //Unreachable statement - compiler-error.
下面这个相同的无限 while
循环却可以正常工作,而且不会发出任何错误,其中我只是用一个布尔变量替换了条件。boolean b=true;
while(b) {
System.out.println("inside while");
}
System.out.println("while terminated"); //No error here.
在第二种情况下,循环后的语句显然是无法到达的,因为布尔变量b仍为true,但编译器却没有任何警告。为什么?
编辑: 下面这个版本的while
陷入了一个明显的无限循环,但即使循环内的if
条件始终为false
,编译器也不会对其下方的语句发出任何编译器错误,因此循环永远不能返回并且可以在编译期间由编译器确定。while(true) {
if(false) {
break;
}
System.out.println("inside while");
}
System.out.println("while terminated"); //No error here.
while(true) {
if(false) { //if true then also
return; //Replacing return with break fixes the following error.
}
System.out.println("inside while");
}
System.out.println("while terminated"); //Compiler-error - unreachable statement.
while(true) {
if(true) {
System.out.println("inside if");
return;
}
System.out.println("inside while"); //No error here.
}
System.out.println("while terminated"); //Compiler-error - unreachable statement.
编辑: 对于if
和while
同样适用。
if(false) {
System.out.println("inside if"); //No error here.
}
while(false) {
System.out.println("inside while");
// Compiler's complain - unreachable statement.
}
while(true) {
if(true) {
System.out.println("inside if");
break;
}
System.out.println("inside while"); //No error here.
}
以下版本的while
也会陷入无限循环。while(true) {
try {
System.out.println("inside while");
return; //Replacing return with break makes no difference here.
} finally {
continue;
}
}
这是因为finally
块总是会被执行,即使在try
块中的return
语句之前就已经遇到了。