-->

How to create specific error messages based on par

2019-09-08 11:02发布

问题:

I'm making a JavaCC program to accept a certain language. I've done this but cannot understand how to use a generated ParseException to determine the issue in the input, and customise the output error message.

So far my code looks like:

try {
  task parser = new task(System.in);
  parser.start();
  System.out.println("YES"); // If accepted print YES.
} catch (ParseException e) {
  System.out.println("NO"); // If rejected print NO.
  switch (e) {
    case 1:
       System.err.println("Some error case")
    case 2:
       ...
  }  
}

Some sources I've looked at are the documentation for ParseException and the JavaCC error handling pages. Neither have helped me understand much better.

If anyone could help/hint I would be really thankful.

回答1:

You can always throw a ParseException with a custom string. For example

void Primary() : {}
{
    <INT> 
|
    "("
|
     {throw new ParseException("At "+getCoords()
                              +" there was \""+ getToken(1).image
                              + "\", but the parser expected either"
                              + " a \"(\" or an integer literal.");}
}

If you are willing to go to enough effort, it should be possible to create a parser that never throws a ParseException that doesn't have a custom message.