gpt4 book ai didi

exception-handling - Antlr 错误/异常处理

转载 作者:行者123 更新时间:2023-12-05 00:28:07 29 4
gpt4 key购买 nike

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

最佳答案

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

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

  • SyntaxErrorListener
  • DescriptiveErrorListener
  • 关于exception-handling - Antlr 错误/异常处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19405913/

    29 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com