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

Sam Harwell sharwell at pixelminegames.com
Sun Jan 11 14:22:34 PST 2009


Here's what I do. This is with the C# target so there are probably a few
differences, but you'll get the idea.

try
{
    MyLexer lexer = new MyLexer( new ANTLRStringStream( text ) );
    CommonTokenStream tokens = new CommonTokenStream( lexer );
    MyParser parser = new MyParser( tokens );
    parser.program();
}
catch ( OperationCanceledException )
{
    // ...
}

Sam

-----Original Message-----
From: antlr-interest-bounces at antlr.org
[mailto:antlr-interest-bounces at antlr.org] On Behalf Of Peter C. Chapin
Sent: Sunday, January 11, 2009 1:14 PM
To: antlr-interest
Subject: [antlr-interest] Passing user defined exceptions through the
parser.

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


List: http://www.antlr.org/mailman/listinfo/antlr-interest
Unsubscribe:
http://www.antlr.org/mailman/options/antlr-interest/your-email-address


More information about the antlr-interest mailing list