antlr/antlr4 · error · NullPointerException
listener cannot be null.
Error message
listener cannot be null.
What it means
addErrorListener(listener) throws NullPointerException when passed null, as documented on the method. The recognizer keeps a list of error listeners and a null entry would break notification loops in reportError. It is a fail-fast argument check, not a recoverable runtime condition.
Source
Thrown at runtime/Java/src/org/antlr/v4/runtime/Recognizer.java:215
if ( t.getType()==Token.EOF ) {
s = "<EOF>";
}
else {
s = "<"+t.getType()+">";
}
}
s = s.replace("\n","\\n");
s = s.replace("\r","\\r");
s = s.replace("\t","\\t");
return "'"+s+"'";
}
/**
* @exception NullPointerException if {@code listener} is {@code null}.
*/
public void addErrorListener(ANTLRErrorListener listener) {
if (listener == null) {
throw new NullPointerException("listener cannot be null.");
}
_listeners.add(listener);
}
public void removeErrorListener(ANTLRErrorListener listener) {
_listeners.remove(listener);
}
public void removeErrorListeners() {
_listeners.clear();
}
public List<? extends ANTLRErrorListener> getErrorListeners() {
return _listeners;
}
View on GitHub (pinned to 7d5770395b)
Solutions
- Remove the null listener before it reaches the call: only add when non-null
- If the intent was to silence errors, call removeErrorListeners() instead of adding a null dummy
- Add a no-op listener (e.g. ANTLRErrorListener with empty methods) when you need a placeholder
Example fix
// before parser.addErrorListener(config.getListener()); // NPE when config returns null // after ANTLRErrorListener l = config.getListener(); if (l != null) parser.addErrorListener(l);
Defensive patterns
Strategy: validation
Validate before calling
Objects.requireNonNull(listener, "listener");
if (listener != null) {
recognizer.addErrorListener(listener);
} Prevention
- Null-check optional listeners at the configuration boundary
- Use removeErrorListeners() to silence, never a null listener
- Annotate listener parameters with @NonNull when your toolchain supports it
When it happens
Trigger: Calling recognizer.addErrorListener(null); wiring listeners from configuration or DI where the value may be unset; copy-pasted setup code that passes a null field before initialization.
Common situations: Optional listener configuration ("add listener only if configured") written without a null branch; listener fields initialized after the recognizer is built; refactors that remove the listener creation but keep the add call.
Related errors
- delegates
- tokenSource cannot be null
- tokens cannot be null
- listener
- This ATN simulator does not support clearing the DFA.
AI-assisted analysis of antlr/antlr4@7d5770395b (2026-08-14).
Data as JSON: /api/errors/69e73336d4b9b34c.
Report an issue: GitHub.