4

After doing some research online I found that this would be the way to catch the exceptions and output my own error messages. For some reason I still cannot seem to catch the errors. Below is the code for a class that overrides antlrs default error handling.

All I want to do is catch the exception from antlr and output to the screen that the syntax is incorrect in a java gui.

public class ExceptionErrorStrategy extends DefaultErrorStrategy {

@Override
public void recover(Parser recognizer, RecognitionException e) {
    throw e;
}

@Override
public void reportInputMismatch(Parser recognizer, InputMismatchException e) throws RecognitionException {
    String msg = "Input is mismatched " + getTokenErrorDisplay(e.getOffendingToken());
    msg += " expecting: "+e.getExpectedTokens().toString(recognizer.getTokenNames());
    RecognitionException ex = new RecognitionException(msg, recognizer, recognizer.getInputStream(), recognizer.getContext());
    ex.initCause(e);
    throw ex;
}

@Override
public void reportMissingToken(Parser recognizer) {
    beginErrorCondition(recognizer);
    Token t = recognizer.getCurrentToken();
    IntervalSet expecting = getExpectedTokens(recognizer);
    String msg = "Missing "+expecting.toString(recognizer.getTokenNames()) + " at " + getTokenErrorDisplay(t);
    throw new RecognitionException(msg, recognizer, recognizer.getInputStream(), recognizer.getContext());
}
}
stacktraceyo
  • 1,235
  • 4
  • 16
  • 22

1 Answers1

6

If all you want to do is report errors, then you are probably looking for the ANTLRErrorListener interface, not the AntlrErrorStrategy interface. The latter is geared towards actually modifying the behavior of the parser in response to errors, e.g. for automatic recovery attempts.

In ANTLRWorks 2, I use the following two classes as my primary implementations of this interface:

Sam Harwell
  • 97,721
  • 20
  • 209
  • 280
  • Do you know what method is actually spitting out the errors to my console? – stacktraceyo Oct 16 '13 at 16:00
  • Vague side question: How painful was it to add support for a new language in Netbeans? – Darien Oct 16 '13 at 17:15
  • @Sam Harwell Hi, I wonder if you have C# syntax for the DescriptiveErrorListener and SyntaxErrorListener above? I'm having trouble finding the syntax for the recognizer part of `public override void syntaxError(Antlr4.Runtime.Recognizer<> recognizer, T offendingSymbol,...` Or a pointer to a C# example that collects errors into a string list instead of printing them to the console during parsing.Thank you – Kevin Aug 02 '20 at 02:05