Antlr错误/异常处理

时间:2013-10-16 14:19:35

标签: exception-handling antlr4

在线进行一些研究之后,我发现这将是捕获异常并输出我自己的错误消息的方法。由于某种原因,我似乎仍然无法捕捉错误。下面是一个覆盖antlrs默认错误处理的类的代码。

我想要做的就是从antlr捕获异常并输出到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 个答案:

答案 0 :(得分:6)

如果您只想报告错误,那么您可能正在寻找ANTLRErrorListener接口,而不是AntlrErrorStrategy接口。后者适用于实际修改解析器的行为以响应错误,例如,用于自动恢复尝试。

在ANTLRWorks 2中,我使用以下两个类作为此接口的主要实现: