Question

Newbie question. Imagine a ParseTreeListener implementation with dozens of enter- and exit- methods which require exception handling. To avoid coding try-catch for each of these 40+ methods individually, I'd prefer a solution which would allow to catch listener's exceptions in a centralized manner and still have a reference to the context (line, position) where the exception was thrown, just like in the imaginary code below:

TestParser parser = new TestParser(tokens);
ParseTreeWalker walker = new ParseTreeWalker();
TestListener listener = new DefaultTestListener();
ParseTree tree = parser.entrynode();

try {
  walker.walk(listener, tree);
} catch (RuntimeException e) {
  LOG.info("Exception at " + tree.getContextWhereExceptionWasThrown());
}

Is it possible in any way?

Was it helpful?

Solution

Given that you have only shown imaginary code, you need to verify the true source and kind of the Exceptions you are seeing.

Walking an otherwise valid parseTree should not throw any Exception other than those you choose to throw. OTOH, the parser will throw exceptions of the type you seem to be concerned with.

If they are indeed parser exceptions, you can catch them explicitly as RecognitionException rather than RuntimeException exceptions. That exception object has the methods you seem to be looking for: getContext, getOffendingToken, etc.

If they are instead occurring in the execution of the walker, you will need to clarify your question regarding the type of exception. If you are throwing the exception, include the relevant token indexes and intervals, obtained from the TerminalNodes and ParserRuleContext objects in the then current context, in a 'one size fits all' exception.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top