Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checked exceptions in visitors

Tags:

antlr4

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?

like image 330
Elena Zucca Avatar asked Sep 04 '13 15:09

Elena Zucca


People also ask

What are checked exceptions examples?

ClassNotFoundException, IOException, SQLException etc are the examples of the checked exceptions.

Which are correct for checked exceptions?

Checked exceptions are checked at compile-time. It means if a method is throwing a checked exception then it should handle the exception using try-catch block or it should declare the exception using throws keyword, otherwise the program will give a compilation error.

When should checked exceptions be thrown?

“If a client can reasonably be expected to recover from an exception, make it a checked exception. If a client cannot do anything to recover from the exception, make it an unchecked exception.” In this way, we can recover the system by accepting another user input file name.

Why checked exceptions are required to be caught?

A Checked exception can be considered one that is found by the compiler, and the compiler knows that it has a chance to occur, so you need to catch or throw it. For example, opening a file. It has a chance to fail, and the compiler knows this, so you're forced to catch or throw the possible IOException .


1 Answers

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);
    }
    
like image 107
Sam Harwell Avatar answered Sep 28 '22 12:09

Sam Harwell