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

问题描述

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

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

定义我自己的访客实现时,我必须重写BaseVisitor的方法(例如,我正在EvalVisitor类的).万一我的方法实现可能引发异常,该怎么办?由于原始方法具有空的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. 处理visitor方法本身内部的异常.
  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);
}

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

10-31 06:20