How to throw an exception in Antlr grammar

I have such a grammar,

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

How to do it? I tried with this

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

But with this, the generated code gives an Error compilation. Since this loactionapth method has no hints in the method signature.

+4
source share
1 answer

Only one way to do this: throw an exception:

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

If the compiler is still complaining (I don’t remember, and I can’t check right now), add 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;}) ; 
+3
source

Source: https://habr.com/ru/post/1438427/


All Articles