Improve exception handling · antlr/antlr4 · Discussion #3162

(Sorry for not wading in earlier... I saw the exchange going by, but just now found the time to sit down and really read them)

The short answer is "yes", I think this addresses my concern that exceptions in a ParseTreeListener were being swallowed.

The slightly longer answer is that, I was working on an ANTLR introduction presentation, and in trying to look into "all the things", I came across the addParseListener(ParseTreeListener) method of the Parser class and wondered what it might be used for. It occurred to me that, maybe I could hook into the Parse and implement some sort of REPL. At this point, you're probably, knowingly, laughing at the naïveté of thinking that work work. In hindsight it was horribly misguided, but a "learning experience". I did work out a REPL, but NOT using a ParseTreeListener.

I agree, wholeheartedly, that semantic concerns need to wait until a parse tree is completed, and have reiterated that many times in answering StackOverflow questions.

That pretty much leaves the question of what ParseTreeListeners attached to the Parser are good for. I see that Parser.TraceListener uses it to get a trace of the parse that can be helpful in understanding/debugging. At this point, I don't know that I've come across another use for attaching them to a parser (for many of the reasons elaborated in this discussion).

That said, IF you find a reason to attach one to a parser, and have reason to throw an exception, I think it's a "good thing" to rethrow that exception in the finally block, so that you can either let it bubble all the way to the top to abort the parse, or perhaps to catch your particular exception somewhere and handle it (I think this still puts the parser into an "I'm outa here" state).

I also think this puts the "solution" in the realm of how to proper handle Java Exceptions in the Java target without much, if any, implications for other language targets.