Throwing Exception from from ANTLR4 visitor

1,367 views
Skip to first unread message

Aravind Kumar

unread,
Apr 1, 2015, 7:43:34 AM4/1/15
to antlr-di...@googlegroups.com

I am an ANTLR newbie. Here is a grammar for which I am trying to write a Visitor class.

grammar extremelysimpleexpr ;

stat : expr ;
expr : sub ;
sub : add ( '-' add )* ;
add : VAL ( '+' VAL )* 
    | VAL
    ;  


VAL : [0-9]+ ;
[ \t\n\r]+ -> skip ;

Vistor.java

 .........
  public Integer vistAdd(ctx) {
       if (some cond) {
          throw new Exception()
       }
  }
 ..........

The problem is I am not able to throw exception since the generated code does not handle exceptions, the method signature does not have throws exception in its signature. Is there any way out of it ?

stack overflow link for this question

Terence Parr

unread,
Apr 1, 2015, 11:06:23 AM4/1/15
to antlr-di...@googlegroups.com
throw a RuntimeException
T
--
You received this message because you are subscribed to the Google Groups "antlr-discussion" group.
To unsubscribe from this group and stop receiving emails from it, send an email to antlr-discussi...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Jim Idle

unread,
Apr 1, 2015, 11:20:40 PM4/1/15
to antlr-di...@googlegroups.com
As Ter says, you can throw an unchecked exception, but actually I question why you want to throw an exception. Exceptions are really for code problems, not for say parsing errors. For errors such as parsing or semantic errors or input problems etc, do not throw exceptions - write a simple error handler class(es) to accumulate problem reports, then print them out at the end of the pass.

Jim

--

Sam Harwell

unread,
Apr 2, 2015, 9:57:31 PM4/2/15
to antlr-di...@googlegroups.com

Jim is exactly right here.

 

Note that if for some reason you need to be able to cancel the parsing operation, the runtime includes a standard exception for this purpose:

http://www.antlr.org/api/Java/org/antlr/v4/runtime/misc/ParseCancellationException.html

 

Sam

Reply all
Reply to author
Forward
0 new messages