【问题标题】:Correct way to add custom exception to Lexer/Parser files in antlr4在 antlr4 中向 Lexer/Parser 文件添加自定义异常的正确方法
【发布时间】:2016-07-19 11:13:26
【问题描述】:

我有一个习惯 ParsingException(String message, int location, String offendingText)

我希望我的解析器在遇到解析/词法分析错误时抛出此异常。

这是正确的吗?

@parser::members
{
  @Override
  public void notifyErrorListeners(Token offendingToken, String msg, RecognitionException ex)
  {
  throw new ParsingException(msg,offendingToken.getStartIndex(),offendingToken.getText());
  }
}
@lexer::members {
    @Override
    public void recover(RecognitionException ex)
    {
 throw new ParsingException(ex.getMessage(),getCharPositionInLine(),ex.getOffendingToken().getText());
        }
          }

我收到一个 UnhandledException 错误。

【问题讨论】:

    标签: java parsing error-handling exception-handling antlr4


    【解决方案1】:

    您应该覆盖 BaseErrorListenersyntaxError 方法,而不是 notifyErrorListenersrecover,因为它在此处描述:Handling errors in ANTLR4

    【讨论】:

    • 好的,但是如果我这样做的话 lexer.addErrorListener(ThrowingParsingExceptionErrorListener.INSTANCE);由于 offendingSymbol 为 null ,如何获取违规文本?谢谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-06-17
    • 1970-01-01
    • 2015-11-09
    • 1970-01-01
    • 2023-04-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多