How do I signal the parser to bail out immediately upon detection of a syntax error, instead of trying to consume tokens until it resynchs?

Terence Parr

ANTLR generates catch-clauses to catch RecognitionException objects thrown by rules (parsers and tree-parsers). Parser rules can throw either RecognitionException objects or TokenStreamException objects; tree parser rules can only throw the former. You have to throw a subclass (in Java anyway) of one of these exceptions and then prevent ANTLR from generating the catch (or manually type in a catch-clause that simply rethrows the exception).

In order to make ANTLR let exceptions slip out of rules and, hence, the parser itself, turn off default error handling with the grammar option as in the following example:

class P extends Parser;
options {
a : ... ;
b : ... ;

Rule a and b will not have catch-clauses and any exception thrown in either will be thrown to the invoking method per normal exception handling. Typically, your main program will call one of the rules and enclose the call in a try/catch:

L lexer = new L(System.in);
P parser = new P(lexer);
try {
catch (RecognitionException e) {
        System.err.println("uh oh: parser error!");