Antlr error/exception handling

2019-02-23 22:29发布

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());
}
}

1条回答
Lonely孤独者°
2楼-- · 2019-02-23 22:53

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:

查看更多
登录 后发表回答