Java - 无法处理 IOException;必须被宣布捕获或被抛出

Java - Can't handle IOException; must be declared caught or to be thrown

参见下面的代码示例 错误信息:

Error:(79, 22) java: unreported exception java.io.IOException; must be caught or declared to be thrown

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

 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();

    }
}

当您将 throws Exception 添加到方法签名时,需要在调用方法时处理异常 'upstream'。

像这样:

    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();

    }
}

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

当您指定方法 "throws (an) Exception" 时,编译器预计会发生异常,因此他可以 "throw" 将其返回给调用者。但是当你使用 "try/catch" 块处理异常时,没有异常可以 "thrown" 返回给方法的调用者(因为已经处理了异常)。

您代码的 "correct" 版本可能是 -

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();
}
}

public AnimalStats() throws IOException{
simulator = new Simulator();
fos = new FileOutputStream("AnimalStats.csv",true);
pw = new PrintWriter(fos);
}

不过还是有很大区别的!

在第一种方法中,方法在自身内部处理异常。它 "doesn't want" 发生异常并返回给调用 AnimalStats() 的函数。

与第一种方法相反,在后者中我们声明方法 throws (an) IOException。我们不打算在方法内处理异常,我们 "throw" 将异常返回给调用 AnimalStats() 的函数并让他们处理它。