在网上做了一些研究后,我发现这将是捕获异常并输出我自己的错误消息的方法。出于某种原因,我似乎仍然无法捕捉到错误。下面是一个覆盖 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());
}
}