I've a snippet
class T{
int y;
public static void main(String... s){
int x;
System.out.println(x);
System.out.println(y);
}
}
Here there are two error, but on compilation why only one error is shown?
The error shown is:
non-static variable y cannot be referenced from a static context
System.out.println(y);
^
But what about the error
variable x might not have been initialized
System.out.println(x);
^
The Java compiler compiles your code in several passes. In each pass, certain kinds of errors are detected. In your example, javac
doesn't look to see whether x
may be initialised or not, until the rest of the code actually passes the previous compiler pass.
@Greg Hewgill has nailed it.
In particular, the checks for variables being initialized, exceptions being declared, unreachable code and a few other things occur in a later pass. This pass doesn't run if there were errors in earlier passes.
And there's a good reason for that. The earlier passes construct a decorated parse tree that represent the program as the compiler understands it. If there were errors earlier on, that tree will not be an accurate representation of the program as the developer understands it. (It can't be!). If the compiler then were to go on to run the later pass to produce more error messages, the chances are that a lot of those error messages would be misleading artifacts of the incorrect parse tree. This would only confuse the developer.
Anyway, that's the way that most compilers for most programming languages work. Fixing some compilation errors can cause other (previously unreported) errors to surface.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With