如何基于JavaCC中的解析异常创建特定的错误消息 [英] How to create specific error messages based on parse exceptions in JavaCC

查看:183
本文介绍了如何基于JavaCC中的解析异常创建特定的错误消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使JavaCC程序接受某种语言.我已经做到了,但无法理解如何使用生成的ParseException来确定输入中的问题,并自定义输出错误消息.

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:
       ...
  }  
}

我看过的一些资料是ParseException和JavaCC错误处理页面的文档.两者都没有帮助我更好地理解.

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.

推荐答案

您始终可以将ParseException与自定义字符串一起抛出.例如

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.");}
}

如果您愿意付出足够的努力,则应该可以创建一个不会抛出没有自定义消息的ParseException的解析器.

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.

这篇关于如何基于JavaCC中的解析异常创建特定的错误消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆