打印多个异常方法调用

时间:2016-04-15 14:32:18

标签: java exception

我在Java中实现了一个编译器类型检查器。如果给定的输入文件(程序)在语义上错误,则我的typeChecking类包含抛出RuntimeExceptions的方法。

现在发生的事情是当我的程序发现错误时,它会抛出异常并且程序终止。我想要的功能是将所有异常消息保存在某处,如果Main类发生异常,则将其打印在typeChecking类。

伪代码示例:

// Main class part of code
public static void main(String[] args){

    call typeChecking method

    if an exception (or more) occurred in the typeChecking class
        then print all the exception messages
    else no semantic errors found
        then do something else
}

我的想法是创建一个静态String数组并在其中添加所有异常消息。然后在我的Main类中,我将检查数组的大小是否为0.如果不是,这意味着其他情况不会发生异常。

有没有更好的方法呢?

1 个答案:

答案 0 :(得分:0)

只需使用try-catch块来捕获异常并使用捕获的异常执行任何操作。即。

// Main class part of code
public static void main(String[] args){
    boolean exceptionOccured = false;
    try{
        call typeChecking method
    }catch(RuntimeException e){
        exceptionOccured = true;
        ...print it or put in an array or whatever.
    }
    if(exceptionOccured)
        do something else
}
相关问题