r/java • u/davidalayachew • Jan 21 '26
Java compiler errors could be more intelligent
I tutored many students over the past several years, and a common pain point is the compiler messages being misleading.
Consider the following example.
interface blah {}
class hah extends blah {}
When I compile this, I get the following message.
blah.java:3: error: no interface expected here
class hah extends blah {}
^
1 error
Most of the students I teach see this, and think that the issue is that blah is an interface, and that they must somehow change it to something else, like a class.
And that's still a better error message than the one given for records.
blah.java:2: error: '{' expected
public record hah() extends blah {}
^
This message is so much worse, as it actually leads students into a syntax rabbit hole of trying to add all sorts of permutations of curly braces and keywords, trying to figure out what is wrong.
If we're talking about improving the on-ramp for learning Java, then I think a core part of that is improving the error --> change --> compile feedback loop.
A much better error message might be this instead.
blah.java:3: error: a class cannot "extend" an interface, only "implement"
class hah extends blah {}
^
1 error
This is powerful because now the language grammar has a more intelligent message in response to an illegal (but commonly attempted) sequence of tokens.
I understand that Java cannot special-case every single illegal syntax combination, but I would appreciate it if we could hammer out some of the obvious ones. extends vs implements should be one of the obvious ones.
View all comments
2
u/josephottinger Jan 21 '26
I'm neutral on this, but: which compiler? There are multiple compilers for Java, each open source; do any of them create better error messages for your purpose? What did ECJ report for the same code?
Have you filed a JEP to maybe get "better error messages" into the platform? Some error messages have gotten better over time even without a JEP, but a JEP gives an easy measure of "what do the people who'd actually have to do the work think" and also gives a measure of doneness. Even the OpenJDK tracker would be a good idea here.
Personally, I think there's some benefit to more explicit error messages, although I also think that "this is an error" forces programmers - including them silly ol' students - to actually look at the code and think through what the error means, which has the ancillary effect of them actually learning stuff instead of just fixing the compilation unit.
It's not that the error message is wrong, after all - you just have a solution in mind, where you mean "this should be
implementsand notextends," for example, but the error might be that they should have used a superclass and not an interface, which is why the error is and should remain, IMO, what it is. "No interface expected here" is, after all, semantically accurate and there are multiple "proper solutions" for it.