如何在Antlr语法中抛出异常

如何在Antlr语法中抛出异常,antlr,antlr3,antlrworks,Antlr,Antlr3,Antlrworks,我有这种语法 locationPath returns [CustomParser xpathParser] :^(LOCATION_PATH relativeLocationPath {**Want to throw a exception if this condition matches**}) |^(LOCATION_PATH absoluteLocationPath {$xpathParser=$absoluteLocationPath.xpathParser;})

我有这种语法

locationPath returns [CustomParser xpathParser]  
    :^(LOCATION_PATH relativeLocationPath {**Want to throw a exception if this condition matches**})
    |^(LOCATION_PATH absoluteLocationPath {$xpathParser=$absoluteLocationPath.xpathParser;})
    ;
怎么做?我试过这个

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

但是使用这个函数,生成的代码会产生编译错误。因为该方法loactionapth没有在方法签名处抛出线索。

只有一种方法可以做到这一点:抛出未检查的异常:

locationPath returns [CustomParser xpathParser]  
 : ^(LOCATION_PATH relativeLocationPath) {throw new RuntimeException("No way!");}
 | ^(LOCATION_PATH absoluteLocationPath {$xpathParser=$absoluteLocationPath.xpathParser;})
 ;
如果编译器仍然抱怨(我不记得了,现在无法测试),请在其前面添加
If(true)

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

好的,我想这会有用的。但是我尝试使用locationPath返回[CustomParser xpathParser]抛出我的自定义异常,然后使用throws子句生成该方法。但是Antlr的工作原理是语法不正确。当我从运行时异常扩展我的异常类时,它就工作了。谢谢你的帮助。