Search code examples
antlrantlr3antlrworks

How to throw an exception in Antlr grammar


I have this kind of a grammar,

locationPath returns [CustomParser xpathParser]  
    :^(LOCATION_PATH relativeLocationPath {**Want to throw a exception if this condition matches**})
    |^(LOCATION_PATH absoluteLocationPath {$xpathParser=$absoluteLocationPath.xpathParser;})
    ;

What is the way to do it? I tried with this one

locationPath returns [CustomParser xpathParser]  
    :^(LOCATION_PATH relativeLocationPath {throw new Exception})
    |^(LOCATION_PATH absoluteLocationPath {$xpathParser=$absoluteLocationPath.xpathParser;})

But with this one the generated code gives compile Error. Because that method loactionapth doesn't have throws clues at method signature.


Solution

  • Only one way to do this: throw an unchecked exception:

    locationPath returns [CustomParser xpathParser]  
     : ^(LOCATION_PATH relativeLocationPath) {throw new RuntimeException("No way!");}
     | ^(LOCATION_PATH absoluteLocationPath {$xpathParser=$absoluteLocationPath.xpathParser;})
     ;
    

    If the compiler still complains (I can't remember, and I'm not able to test right now), add an if(true) in front of it:

    locationPath returns [CustomParser xpathParser]  
     : ^(LOCATION_PATH relativeLocationPath) {if(true) throw new RuntimeException("No way!");}
     | ^(LOCATION_PATH absoluteLocationPath {$xpathParser=$absoluteLocationPath.xpathParser;})
     ;