在FileWriter上使用try catch

时间:2017-10-27 12:11:33

标签: java filewriter

我对FileNotFoundExcpetion有疑问。接口我定义了方法名称,包括"抛出FileNotFoundExcpetion"。

public static void writeAssignment(ArrayList<String> assignment, String filename) throws FileNotFoundException {

    try {
        FileWriter writer = new FileWriter(filename);
        for (String str : assignment) {
            writer.write(str + "\n");
        }
        writer.close();

    } catch (IOException e) {
        System.err.print("Something went wrong");
    }
}

这是处理异常的正确方法吗?当我写入我正在使用文件编写器创建的文件时,如果我在方法中创建文件,怎么可能找不到文件?

2 个答案:

答案 0 :(得分:2)

IOExceptionFileNotFoundException的超类。因此,IOException的catch块也会捕获每个FileNotFoundException

您应该按如下方式实现该功能:

public static void writeAssignment(ArrayList<String> assignment, String filename) throws FileNotFoundException {

    try (FileWriter writer = new FileWriter(filename)) {
        for (String str : assignment) {
            writer.write(str + "\n");
        }
    } catch (FileNotFoundException e) {
        throw e; // catch and re-throw
    } catch (IOException e) {
        System.err.print("Something went wrong");
    }
}

答案 1 :(得分:-1)

您可以捕获Exception而不是IOException

public static void writeAssignment(ArrayList<String> assignment, String filename) throws FileNotFoundException {

try {
    FileWriter writer = new FileWriter(filename);
    for (String str : assignment) {
        writer.write(str + "\n");
    }
    writer.close();

} catch (Exception e) {
    e.printStackTrace();
}
}

通过此类型编码,您可以查看/了解异常的层次结构。 如果你想执行你的程序是否被捕获异常,你可以使用 finally 块。你将关闭你的作家。