7

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

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?

Bart Kiers
  • 166,582
  • 36
  • 299
  • 288

1 Answers1

5

You have two options:

  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);
    }
    
Sam Harwell
  • 97,721
  • 20
  • 209
  • 280
  • Hmm the point is that my visit method *should* have a throws clause in its interface. For instance, in the example of the EvalVisitor class, it would make sense to have the following signature for the visit methods: public Integer visit_(...) throws UndefinedId, meaning that the visit throws an exception if some identifier is encountered which has not been assigned before. It seems that this cannot be obtained by reusing ANTLR code, and that one should use unchecked exceptions instead, but they are less informative for a client. – Elena Zucca Sep 05 '13 at 14:44
  • You can write your code in proper Java style by writing your visitor implementation in such a way that the `UndefinedId` exception will never be thrown. One possibility is using a separate visitor solely to gather information about definitions, and then throwing an exception (outside of visitor code) if the result of that visitor suggests something is not defined. By the time you are operating in the visitor you describe above, all items are defined and the `throws` clause becomes unnecessary. – Sam Harwell Sep 05 '13 at 16:52
  • 1
    I think having another visitor does not change the problem, what you suggest is, rather, to model the undefined case as an additional return value rather than an exception. That is, the visit method will have signature public Integer_Or_Undefined visit_(...). This is a possible and clean solution but, of course, you loose the benefit of automatic error propagation. – Elena Zucca Sep 05 '13 at 17:28