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());
}
}
If all you want to do is report errors, then you are probably looking for the
ANTLRErrorListener
interface, not theAntlrErrorStrategy
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:
SyntaxErrorListener
DescriptiveErrorListener