By default, ANTLR sends all errors to standard error, but we can change the destination and the content by providing an implementation of interface ANTLRErrorListener. The interface has a syntaxError method that applies to both lexers and parsers. Method syntaxError receives all sorts of information about the location of the error as well as the error message. It also receives a reference to the parser, so we can query it about the state of recognition.
For example, here’s an error listener (in test rig TestE_Listener.java) that prints out the rule invocation stack followed by the usual error message augmented with offending token information:
public static class ...