I am attempting to test a language created in Visual Studio using Antlr4 (target language is C#). Everything works wonderful, but I need a way to access exceptions that are thrown while parsing.
I have implemented a listener that extends IAntlrErrorListener<IToken> as follows:
public class SettlementErrorListener : IAntlrErrorListener<IToken>
{
public static SettlementErrorListener INSTANCE = new SettlementErrorListener();
public void SyntaxError(IRecognizer recognizer, IToken offendingSymbol, int line, int charPositionInLine, string msg, RecognitionException e)
{
throw new Exception(msg + " on line " + line + ";character position " + charPositionInLine + e.Message);
}
}
Everything works fine and dandy, and I could work with this. It throws the exception because something parsed wrong down the line.
But what I want it to be able to access the exception field associated with each context. In other words I want exception in the context to not be null:
If I just run this line of code:
var ctx = p.solution();
No matter what, the exception field is not populated just running through. Debugging and STEPPING OVER also does not catch the RecognitionException.
However if I go back and STEP INTO the actual rule, the exception is caught and passed back on up through the contexts which makes it available in the ctx variable.
catch (RecognitionException re) {
_localctx.exception = re;
_errHandler.ReportError(this, re);
_errHandler.Recover(this, re);
}
finally {
ExitRule();
Can some please explain this behavior to me?