簡體   English   中英

如何在antlr4訪問者方法中拋出異常?

[英]How to throw an exception in antlr4 visitor methods?

我正在使用visitor方法來評估解析后的代碼。 對於函數調用,我想通過讓return語句規則的visitor方法拋出自定義異常ReturnException來處理return語句。 這是為了在函數調用的visitor方法中,它可以捕獲return語句異常並返回我保存在異常對象中的返回值。 但是,當我將try catch放入我從BaseVisitor類重寫的VisitReturnStatement函數時,我收到錯誤:

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

錯誤: 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;

我認為這是因為我沒有在方法中聲明的異常,如:

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

但是,如果我添加throws Exception ,我得到一個錯誤Exception Exception is not compatible with throws clause in CalculatorBaseVisitor<Value>

您不能從訪問者方法中拋出已檢查的異常,因為訪問者接口不會聲明任何拋出的異常。 你唯一的選擇是改變你的例外通過擴展未被選中RuntimeException ,來包裝你的異常RuntimeException S或重新構造你的代碼不使用異常。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM