Java - 无法处理IOException;必须被宣布被抓或被抛出[重复]

问题描述 投票:0回答:2

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

错误:(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();

    }
}
java ioexception
2个回答
0
投票

向方法签名添加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();

    }
}

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


-1
投票

当您指定方法“throws(an)Exception”时,编译器期望发生异常,因此他可以将其“抛出”回调用者。但是当你使用“try / catch”块处理异常时,没有异常可以“抛出”回方法的调用者(因为已经处理了异常)。

您的代码的“正确”版本将是 -

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

但是有一个很大的区别!

在第一种方法中,该方法在其自身内处理异常。它“不希望”发生异常并返回给调用AnimalStats()的函数。

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

© www.soinside.com 2019 - 2024. All rights reserved.