简体   繁体   中英

How to throw an exception in antlr4 visitor methods?

I am using the visitor method to evaluate the code as it's parsed. For function calls, I want to handle the return statements by having the visitor method for the return statement rule throw a custom exception ReturnException . This is so that in the visitor method for the function call, it can catch return statement exception and return the return value I saved in the exception object. However, I get an error when I put the try catch in my VisitReturnStatement function that I override from the BaseVisitor class:

try { 
        throw new ReturnStatementException("Return statement", retValue); 
    } 
    catch(ReturnStatementException e) { 
        System.out.println("Return statement exception caught"); 
        throw e;
    } 

The error: error: unreported exception ReturnStatementException; must be caught or declared to be thrown throw e; error: unreported exception ReturnStatementException; must be caught or declared to be thrown throw e;

I figured it's because I do not have the exception declared in the method like:

@Override 
public Value visitReturnStatement (CalculatorParser.ReturnStatementContext ctx) throws Exception {...}

But if I add the throws Exception , I get an error Exception Exception is not compatible with throws clause in CalculatorBaseVisitor<Value>

You can't throw checked exceptions from visitor methods because the visitor interface does not declare any thrown exceptions. Your only options are to change your exceptions to be unchecked by extending RuntimeException , to wrap your exceptions in RuntimeException s or to re-structure your code to not use exceptions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM