Search code examples
javaparsingjavaccparser-generator

Try-catch block in JavaCC grammar


I am trying to implement Error Reporting and Recovery in JavaCC grammar

I have mentioned the following code in .jjt grammar file

void Stm() :
{}
{
  try {
    (
      IfStm()
    |
      WhileStm()
    )
  }catch (ParseException e) {
    error_skipto(SEMICOLON);
  }
}


void error_skipto(int kind) {
  ParseException e = generateParseException();  // generate the exception object.
  System.out.println(e.toString());  // print the error message
  Token t;
  do {
    t = getNextToken();
  } while (t.kind != kind);
}

When I execute the command jjtree CMinus.jjt I get following error:

Reading from file CMinus_ragu.jjt . . . Error parsing input: org.javacc.jjtree.ParseException: Encountered " "{" "{ "" a t line 111, column 30. Was expecting one of: "throws" ... ":" ... "#" ...

What is the error in the code and how should I handle the error recovery?


Solution

  • The keyword JAVACODE should be added before error handler code in grammar file. Therefore the method should appear as follows:

    JAVACODE
    void error_skipto(int kind) {
      ParseException e = generateParseException();  // generate the exception object.
      System.out.println(e.toString());  // print the error message
      Token t;
      do {
        t = getNextToken();
      } while (t.kind != kind);
    }
    

    This is because the keyword JAVACODE should be added before using java style production.