0
votes

How to catch the exception in the lexer? In parser if a rule is failed (or mismatched with the given input stream ) Antlr will throw the exception and we can easily catch this exception.Catch the exception in the lexer in Antlr3.Ref:Error handeling in antlr 3.0...

attribute  :
      Value1 integer1["Value1"] { System.out.println("Accepted"); }
   |  Value2 integer2["Value2"] { System.out.println("Accepted"); }
   ;
catch[Exception e] {System.out.println("General error Reported");}

It will work in parser.But how can I catch the exception in the lexer itself?.Say in parser I am having the rule like

str:STRING|DIGIT;

and in lexer STRING is defined as

STRING : ('"' 'a'..'z' '"');  

My input stream is "God"....If I miss the double quote or if I put the extra double quote then I want that exception should be caught in the lexer itself...Is there any method to do this? Is it possible?

1

1 Answers

0
votes

Override one or more of the following methods to use ANTLR's own exception handling (this applies to both lexer and parser) - note that this applies only to exceptions caused by input mismatch:

  • emitErrorMessage() - to handle how the message is displayed to user
  • getErrorHeader() - to change how error message header is created
  • getErrorMessage() - to change how the description of error is created
  • displayRecognitionError() - to change how the message is created from the exception, or to completely change how the exception is handled

The key difference between ANTLR's lexer and parser is that in lexer, there is no start rule or "current" rule - the lexer tries to match all available rules in parallel. So if a mismatch occurs, it cannot be attributed to any particular rule (so it also cannot be handled in any particular rule using a catch block).