Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does the Java compiler only report one kind of error at a time?

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);
                       ^
like image 331
Mohammad Faisal Avatar asked Dec 01 '22 07:12

Mohammad Faisal


2 Answers

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.

like image 110
Greg Hewgill Avatar answered Dec 06 '22 19:12

Greg Hewgill


@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.

like image 30
Stephen C Avatar answered Dec 06 '22 19:12

Stephen C