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?
ClassNotFoundException, IOException, SQLException etc are the examples of the 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.
“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.
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 .
You have two options:
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With