[antlr-interest] Passing user defined exceptions through the parser.

Peter C. Chapin pcc482719 at gmail.com
Sun Jan 11 11:13:44 PST 2009


Hello! I'm fairly new to ANTLR so forgive me if this seems like a simple
question.

I'm using ANTLR to generate a Java parser. I would like to raise an
exception of my own inside a method called as part of a rule action. In
particular, if I discover that the input contains a language feature I'm
not (yet) ready to handle, I want to throw an exception that I'm calling
UnsupportedConstructException. This is not a parse error; the input
might be a perfectly legal sentence in the input language. However, my
program just isn't up for dealing with every construct in that language.

Here is a snippet of my grammar.

component
    : REMOTABLE? k=comp_kind IDENTIFIER
       { makeComponentInfo($IDENTIFIER.text, $k.componentKind); }
      component_specification implementation?
       { commitComponentInfo(); } ;

The makeComponentInfo method will raise the exception if it doesn't like
the component kind it has been given. The problem is that the parser
won't compile because the method in the parser for handling the
component rule does not declare that it throws this exception (and
similarly for all the rules that directly or indirectly call the
component rule).

I want to catch this exception at the top level... once it leaves the
ANTLR generated parser entirely. There I will tell the user that I can't
deal with the program because it contains an unsupported kind of
component, blah, blah. My question is: what's the best way for me to
deal with this? Is there some "nice" way for me to get my exception to
pass through all the code generated by ANTLR? I understand that I could
define my exception to be a subclass of RuntimeException, but that
seems... well... wrong.

As an aside this appears to be a good example of why statically checked
exception specifications are not always desirable.

Peter



More information about the antlr-interest mailing list