[antlr-interest] Re: Bad exception handling ?

antlrlist antlrlist at yahoo.com
Tue Aug 5 01:53:20 PDT 2003


Hi julius.

In my opinion you have two options. The first one consists on turning
off default exception handling. This way your exceptions will make
your parser to stop when an error happens. You can turn default
exception handling off by using the defaultErrorHandler option off
(more information in http://www.antlr.org/doc/options.html#_bb9)

The second option consists in using your own exception handler for
that rule. In the exception handler's code, you should arrange it for
aborting the parsing. There are lots of ways for doing this, one of
them being launching your own exception (i'd recommend a subclass of
java.lang.RuntimeException).

For example, let's imagine that you've implemented a subclass of
RuntimeException called MyParsingException. Then in your rule you'd
have to write:

rule: (AK)? (KI)? EC (ZD)? ;
exception catch [RecognitionException re]
{
 throw new MyParsingException(
  "Error while parsing the source: "+re.getMessage() );
}

You should use this solution if you only want to abort parsing on this
rule, an not on the others.

Cheers,

Enrique


--- In antlr-interest at yahoogroups.com, "julius_siska"
<julius_siska at y...> wrote:
> Hi,
> 
> I have following problem. I have grammar file with tokens AK, KI, EC 
> and ZD. One of parsing rules is:
>    (AK)? (KI)? EC (ZD)?
> Parsed input stream contains just tokens:
>    AK ZD    
> (obviously missing EC token)
> 
> Relevant part of generated Java parser code to my grammar is as 
> follows (for brevity I ommit unnecessary curly braces):
> 
>       switch ( LA(1)) {
> 	case AK:
> 	        match(AK);
> 	        break;
> 	case KI:
> 	case EC:
> 		break;
> 	default:
> 		throw new NoViableAltException(LT(1), getFilename());
>       }
>       switch ( LA(1)) {
> 	case KI:
> 		match(KI);
> 		break;
> 	case EC:
> 		break;
> 	default:
> !!!		throw new NoViableAltException(LT(1), getFilename());
>       }
>       match(EC);
>    
> During parsing, is in line marked by !!! thrown NoViableAltException, 
> because in the stream is not the EC token present. 
> But the parser just print error message line:xxx:y: unexpected token 
> ZD. Thrown exception is caught somewehre inside ANTLR, but I would 
> need to have it thrown outside to know that something is wrong in my 
> program. I think this exception should be thrown from parser.file() 
> method.
> 
> Can somebody help me, how to get this exception out of ANTLR and into 
> my program where I can handle it and reject such input stream ?
> 
> Thanks in advance,
>    Julius Siska


 

Your use of Yahoo! Groups is subject to http://docs.yahoo.com/info/terms/ 




More information about the antlr-interest mailing list