I'm using ANTLR to parse logical expressions in a Java tool I'm writing, and I'm having issues because passing invalid input strings to the generated ANTLR lexer and parser doesn't cause any exceptions. Instead of throwing a RecognitionException, like I would expect, the generated files just print the error message to the console and return as if no errors occurred, causing my program to crash when it runs into the empty data later.
I used ANTLRWorks version 1.4.3 to generate the files, and it seems like there should be some sort of option to have it actually throw errors rather than print to the console, but I haven't found anything. Does anyone know how to get ANTLR to actually throw error messages? I saw that this same issue in C# was solved by using an older version of ANTLR, is that what I need to do?
EDIT: After Bart pointed me in the direction of what I was looking for, I found this page
https://theantlrguy.atlassian.net/wiki/display/ANTLR3/Migrating+from+ANTLR+2+to+ANTLR+3
whose "Error handling" section had code that did what I want more exactly. To change the way ANTLR catches exceptions, you can say this in the grammar file:
@rulecatch {
catch (RecognitionException e) {
throw e;
}
}
This forces ANTLR to throw the exception instead of handling it and recovering. There's also some stuff in that section about overriding the mismatch and recovery functions to make sure all possible exceptions are thrown.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…