尝试catch,Java eclipse没有捕获异常

时间:2016-05-04 08:27:34

标签: java exception exception-handling

public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    System.out.println("Enter file name:");
    String name = sc.nextLine();
    creatingfeatures(name, "part1");
}

public static void creatingfeatures(String filename, String type) {
    String outputFile = "../data/" + type + "/" + type + ".csv";
    System.out.println("This is the output file: " + outputFile);
    try {
        CsvWriter csvOutput = new CsvWriter(new FileWriter(outputFile, true), ',');
        for (int i = 0; i < 10 ; i++) {
            csvOutput.write(i);
            csvOutput.endRecord();
        }
        csvOutput.close();
    }
    catch (IOException e) {
        System.out.println("Please enter another file name (wrong name given)");
        System.exit(0);
    }
}

大家好,当我使用无效的文件名时(即未找到文件时),未打印catch下的消息。谁知道为什么?

2 个答案:

答案 0 :(得分:4)

documentation很明显,它不会为提供给FileWriter的错误文件名提供异常,而是创建新文件(如果不存在)。此外,如果它无法在所需位置创建文件,则会抛出IOException。只需检查位置,它应该在那里创建文件。

  

在给定带有布尔值的文件名的情况下构造FileWriter对象   指示是否附加所写的数据。

     

参数:       fileName String依赖于系统的文件名。       如果为true,则追加布尔值,然后将数据写入文件的末尾而不是开头。抛出:       IOException如果指定文件存在但是目录而不是常规文件,不存在但无法创建,或不能   因任何其他原因而被打开

答案 1 :(得分:0)

您正在捕捉IOExceptions

catch (IOException e) {
    System.out.println("Please enter another file name (wrong name given)");
    System.exit(0);
}

如果您有其他类型的例外,您也必须抓住它们。 使用:

catch (Exception e) {
    System.out.println("Other kind of exception");
    System.exit(0);
}

代替或者除了捕获任何类型的异常

catch (IOException e) {
    System.out.println("Please enter another file name (wrong name given)");
    System.exit(0);
}catch (Exception e) {
    System.out.println("Other kind of exception");
    System.exit(0);
}