[antlr-interest] Parser Generation: How to catch an exception within an rule?

Johannes Luber jaluber at gmx.de
Fri Mar 9 13:55:41 PST 2007


luciano mantuaneli wrote:
> Greetings!
> I have a rule called identifierStar, which throws an
> MyOwnCheckedException exception.
> I have another rule called importDefinition, which invokes relu x. My
> question is how can I catch the MyOwnCheckedException exception?

Add following lines to your rule:

> importDefinition
>     options {defaultErrorHandler = true;}
>     { boolean isStatic = false; String imp = "";}
>     :    i:"import"^ {#i.setType(IMPORT);} ( "static"!
> {#i.setType(STATIC_IMPORT);} )? imp=identifierStar SEMI!
>     ;
	exception
	catch [StarImportException e] {
		System.err.println("error");
	}
> 
> 
> identifierStar returns[String result = ""] throws StarImportException{
>     StringBuilder sb = new StringBuilder("");
> }
>     :    i:IDENT{sb.append(i.getText());}
>         ( DOT^ i2:IDENT {sb.append("." + i2.getText());})*
>         ( DOT^ STAR {throw new StarImportException();})?
>         {
>             result = sb.toString();
>         }
>     ;

Best regards,
Johannes Luber



More information about the antlr-interest mailing list