如何删除异常处理程序?

时间:2012-10-25 03:04:49

标签: java exception-handling

我想从这段代码中删除异常处理程序,因为我不明白它存在的原因,我相信它在我的代码阶段没有做任何事情。 我有这个:

public void ToFile(){
               try{
                   PrintWriter pw = new PrintWriter(new FileWriter(file, false));

                    for (String st:stringarray){ 
                          pw.println(st);
                          pw.close();
                            }
                    }catch(Exception exception)
                    {}
            }

当我删除异常部分时,我将其转换为此,但它给了我错误......:

public void ToFile(){

                            PrintWriter pw = new PrintWriter();
                            for (String st:items){ 
                                    pw.println(srtingarray);
                                    pw.close();
                            }

            }

我该怎么办? 修改 错误:找不到适合PrintWriter的构造函数。

3 个答案:

答案 0 :(得分:3)

尝试这样的事情:

public void toFile() throws IOException {
    PrintWriter pw = new PrintWriter(new FileWriter(file, false));

    for (String str: items){ 
        pw.println(str);
    }

    pw.close();
}

写入失败时,使用PrintWriter可以生成IOException。您可以捕获并处理函数中的那些,或者添加一个throws子句,该子句允许异常向上传播给调用者。

(我还将close()调用移到了循环之外并修正了您使用pw的方式。)

知道添加throws子句并不能完全解决您的问题,因为调用者仍然需要处理异常。它只是将问题提升一级。不过,这是正确的做法。 没有办法完全忽略IOException。这些函数可能会出错,Java会强制您在某些时候处理这​​些错误。这是好事

如果你想在这里处理异常,你可以这样做。在catch子句中执行 something 是个好主意。看到catch(Exception e) { }有一个空的处理程序会让小Knuth感到难过。

public void toFile() {
    try {
        PrintWriter pw = new PrintWriter(new FileWriter(file, false));

        for (String str: items){ 
            pw.println(str);
        }

        pw.close();
    }
    catch (IOException exception) {
        exception.printStackTrace();
    }
}

答案 1 :(得分:3)

异常处理程序是“处理” 1 当无法打开文件时new FileWriter(file, false)可能抛出的IOException。如果您不打算处理它,则必须在方法签名中声明它:

public void toFile() throws IOException {
    PrintWriter pw = new PrintWriter(new FileWriter(file, false));
    for (String st : items) { 
        pw.println(st);
    }
    pw.close();
}

我也借此机会修复方法名称。切勿使用大写字母开始方法名称。这是一个主要的风格错误。

我修复了另外2个编译错误和一个错误。 (看看你是否能发现它......并找出它为什么是一个错误。)

最后,真正正确的写法是:

// Java 7
public void toFile() throws IOException {
    try (PrintWriter pw = new PrintWriter(new FileWriter(file, false))) {
        for (String st : items) { 
            pw.println(st);
        }
    }
}

// pre-Java 7
public void toFile() throws IOException {
    PrintWriter pw = new PrintWriter(new FileWriter(file, false))) {
    try {
        for (String st : items) { 
            pw.println(st);
        }
    } finally {
        pw.close();
    }
}

你需要这样做,以便FileWriter总是被关闭......即使在循环中抛出了意外的异常。


1 - 事实上,原来的catch (Exception exception) { }真的太可怕了。首先,它只是在没有说什么的情况下吞噬异常。其次,它是为Exception做的...而且包括一大堆例外NullPointerException,很可能是一个bug的证据。不要压缩异常,特别是不要试图像这样“处理”Exception

答案 2 :(得分:0)

异常的原因是在循环的第一次迭代之后,您正在关闭PrintWriter对象。

相关问题