Checked exceptions in visitors
Asked Answered
A

1

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?

Antibiotic answered 4/9, 2013 at 15:58 Comment(2)
"The Book?" Could you provide a link, or at least a title?Peru
@rogaos, good point, but in this case there is just one possibility (which I edited in the question).Tilla
H
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);
    }
    
Hyperform answered 5/9, 2013 at 4:25 Comment(3)
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.Antibiotic
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.Hyperform
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.Antibiotic

© 2022 - 2024 — McMap. All rights reserved.