访问者中的已检查异常 [英] Checked exceptions in visitors

查看:30
本文介绍了访问者中的已检查异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习 ANTLR4,我以前没有使用解析器生成器的经验.

I am learning ANTLR4 and I have no previous experience with parser generators.

当我定义自己的访问者实现时,我必须覆盖 BaseVisitor 的方法(我正在寻找位于 本书第 40 页).如果我的方法实现可能抛出异常,我该怎么办?我不能使用受检异常,因为原始方法有一个空的 throws 子句.我应该使用未经检查的异常吗?(这似乎是一个糟糕的 Java 设计).例如,假设在 EvalVisitor 类中,我希望方法 visitId(第 41 页)抛出用户定义的异常,比如 UndefinedId,而不是返回 0.我应该如何编写代码?

When I define my own visitor implementation, I have to override methods of the BaseVisitor (I am looking for instance at the EvalVisitor class at page 40 of the book). In case my method implementation possibly throws an exception, what should I do? I cannot use a checked exception since the original method has an empty throws clause. Am I expected to use unchecked exceptions? (this seems a bad Java design). For instance, assume that in the EvalVisitor class I want method visitId (page 41) to throw a user-defined exception, say UndefinedId, rather than returning 0. How should I write my code?

推荐答案

您有两个选择:

  1. 处理访问者方法本身内部的异常.
  2. 将已检查的异常包装在未检查的异常中.一种可能性是 ParseCancellationException,但您必须自己确定这在您的应用程序中是否有意义.

  1. Handle the exception inside the visitor method itself.
  2. Wrap your checked exception in an unchecked exception. One possibility is ParseCancellationException, but you'll have to determine for yourself whether or not that makes sense in your application.

try {
    ...
} catch (IOException ex) {
    throw new ParseCancellationException(ex);
}

这篇关于访问者中的已检查异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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