Error handeling in antlr 3.0

左心房为你撑大大i 提交于 2019-12-07 05:45:30

"Catch blocks are no longer prefixed with 'exception' keyword", so your attribute rule would be:

attribute  :
      Value1 integer1["Value1"] { System.out.println("Accepted"); }
   |  Value2 integer2["Value2"] { System.out.println("Accepted"); }
   ;
catch[Exception e] {System.out.println("General error Reported");}

Next, you have overriden lexer's reportError method, not the one of the parser (where inbound check is invoked).

To make the parser throw error instead of recovery you can copy reportError to @parser::members section and then you can get "General error Reported".

But if you want not to stop antlr's recovery mechanism, but to make error messages more informative, you can read this free excerpt from The Definitive ANTLR Reference and define getErrorMessage method:

public String getErrorMessage(RecognitionException e, String[] tokenNames)
{
    List stack = getRuleInvocationStack(e, this.getClass().getName());
    String msg = null;
    if ( e instanceof NoViableAltException ) {
       NoViableAltException nvae = (NoViableAltException)e;
       msg = " no viable alt; token="+e.token+
          " (decision="+nvae.decisionNumber+
          " state "+nvae.stateNumber+")"+
          " decision=<<"+nvae.grammarDecisionDescription+">>";
    }
    else if(  e instanceof FailedPredicateException  ) {
       FailedPredicateException fpe = (FailedPredicateException)e;
       msg = "failed predicate; token="+fpe.token+
              " (rule="+fpe.ruleName+" predicate="+fpe.predicateText+")";
    }
    else {
       msg = super.getErrorMessage(e, tokenNames);
    }
    return stack+" "+msg;
}
public String getTokenErrorDisplay(Token t) {
    return t.toString();
}   
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!