I was doing some small programs in java. I know that if I write while(true);
the program will freeze in this loop. If the code is like that:
Test 1:
public class While {
public static void main(String[] args) {
System.out.println("start");
while (true);
System.out.println("end");
}
}
The compiler throws me the error:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
Unreachable code
at While.main(While.java:6)
I didn't know that this error exists. But I got why it is thrown. Of course, line 6 was unreachable, causing a compilation problem. Then I tested this:
Test 2:
public class While {
public static void main(String[] args) {
System.out.println("start");
a();
b();
}
static void a() {
while(true);
}
static void b() {
System.out.println("end");
}
}
For some reason the program ran normally (The console printed "start" and then froze). The compiler couldn't check inside of void a()
and see that it isn't reachable. To be sure I tried:
Test 3:
public class While {
public static void main(String[] args) {
System.out.println("start");
a();
System.out.println("end");
}
static void a() {
while(true);
}
}
Same result as Test 2.
After some research I found this question. So, if the code inside the parentheses is a variable the compiler wouldn't throw the exception. That makes sense, but I don't think that the same applies to voids
.
Q: So, why does the compiler just throw me the error at Test 1, if void b()
(Test 2) and System.out.println("end");
(Test 3) isn't reachable?
EDIT: I tried Test 1 in C++:
#include <iostream>
using namespace std;
int main()
{
cout << "start" << endl;
while(true);
cout << "end" << endl;
return 0;
}
The compiler didn't throw any errors, then I got the same result as Test 2 and as Test 3. So I suppose this is a java thing?
question from:https://stackoverflow.com/questions/24130399/whiletrue-loop-throws-unreachable-code-when-isnt-in-a-void