Подивіться на наступний нескінченний whileцикл у Java. Це спричиняє помилку під час компіляції для твердження під ним.
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є істинною, і все-таки компілятор взагалі не скаржиться. Чому?
Редагувати: Наступна версія програми 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блок завжди виконується, навіть якщо returnоператор зустрічається перед ним у самому tryблоці.