How to create specific error messages based on parse exceptions in JavaCC

北城余情 提交于 2019-12-12 01:35:48

问题


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.



来源:https://stackoverflow.com/questions/36800025/how-to-create-specific-error-messages-based-on-parse-exceptions-in-javacc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!