[antlr-interest] v3: Throwing exception on an error

Mark Mandel mark.mandel at gmail.com
Tue Jan 23 14:48:19 PST 2007


All,

I wanted to have my parser be able to throw an exception if an error
occured during the process of evaluating my grammer, and this is what
I came up with.

I figured I would share it with you to see if there was a better way
of doing this:

I have this in both my lexer and my parser, but I'll just show you one:

@parser::members {
	private RecognitionException recognitionException;
	private String errorMessage;
	
	public void displayRecognitionError(String[] tokenNames,
RecognitionException e)
	{
		if(!hasError())
		{
			setRecognitionException(e);
			setErrorMessage(getErrorMessage(e, tokenNames));		
		}
	}
	
	public RecognitionException getRecognitionException()
	{
		return recognitionException;
	}
	
	private void setRecognitionException(RecognitionException e)
	{
		recognitionException = e;
	}
	
	public boolean hasError()
	{
		return (getRecognitionException() != null);
	}
	
	public String getErrorMessage()
	{
		return errorMessage;
	}
	
	private void setErrorMessage(String error)
	{
		errorMessage = error;
	}
}

Basically this just traps the first error as it comes through.  From
there, after a calling my parser, I can ask my lexer and my parser if
they have 'haveError()', get the error message, and the
RecognitionException and throw my own exception from there with the
details.

It seems to work very well, so I'm not complaining.

Is there a better way to do this?

Mark

-- 
E: mark.mandel at gmail.com
W: www.compoundtheory.com


More information about the antlr-interest mailing list