首页 > 解决方案 > Java - 无法处理 IOException;必须宣布被抓住或被扔掉

问题描述

请参阅下面的代码示例错误消息:

错误:(79, 22) java: 未报告的异常 java.io.IOException; 必须被抓住或宣布被扔掉

为什么我会得到这个?我该如何解决?

 public AnimalStats() throws IOException{
    simulator = new Simulator();
    try{
        fos = new FileOutputStream("AnimalStats.csv",true);
        pw = new PrintWriter(fos);
    }
    catch(IOException e) {
        System.out.println("Error has been caught!");
        e.printStackTrace();

    }
}

标签: javaioexception

解决方案


当您将 throws Exception 添加到方法签名时,这要求在调用方法的点“上游”处理异常。

像这样的东西:

    try{
     AnimalStats();

}catch(IOException ex){
     // DO SOMETHING
    }

但是,如果您在这一点上让签名保持沉默,您可以使用您的 try/catch 块在方法内处理异常,就像您所做的那样。但为此,您需要从方法签名中删除 throws。像这样:

public AnimalStats(){
    simulator = new Simulator();
    try{
        fos = new FileOutputStream("AnimalStats.csv",true);
        pw = new PrintWriter(fos);
    }
    catch(IOException e) {
        System.out.println("Error has been caught!");
        e.printStackTrace();

    }
}

您可以使用任何一种方法。


推荐阅读