Reputation: 93
I followed the instructions for error handling at the antlr website http://www.antlr2.org/doc/err.html (it says antlr2 but I couldn't find an alternative for antlr4) and wrote the exception handling for my rule as below.
subStmt :
(visibility WS)? (STATIC WS)? SUB WS? ambiguousIdentifier (WS? argList)? endOfStatement
block?
END_SUB
;
exception
catch [RecognitionException ex] {
}
But when I try to generate the Parser for the grammar it fails as below: java -jar ../Downloads/antlr-4.7-complete.jar vba.g4 -package vba -o out error(50): vba.g4:500:4: syntax error: 'catch' came as a complete surprise to me while matching rule preamble
Any help is much appreciated.
Upvotes: 0
Views: 758
Reputation: 18359
Antlr4 is quite different to Antlr2. Start by having a look at this question (and the answer):
How to implement error handling in ANTLR4
Update with a simple approach:
For error reporting, the basic approach is to make a class that implements the ANTLRErrorListener
interface. BaseErrorListener
has empty implementations for all the methods so you only need to implement the ones you care about. You probably care about syntaxError()
the most.
On your parser object, call removeErrorListeners()
to clear the internal error listener, and then call addErrorListener()
with an instance of the class you want to handle your errors.
You will then get syntaxError()
calls on that class when errors are encountered during a parse.
The other methods might (or might not) let you do what you want to do; I haven't used this interface to recover from parse errors.
For recovering from particular errors, you can implement a class with the ANTLRErrorStrategy
interface. That gets complicated; see DefaultErrorStrategy
for the default implementation.
A very simple approach is to deal with the possible errors in your grammar. Not sure how far you can go with this, but this is likely to be the easiest approach.
Upvotes: 1