如果没有捕获,嵌套尝试是否有任何用途?

时间:2019-04-15 05:33:41

标签: java exception

从Java书籍的以下代码中查找

public void writeFile(String fileName, String content){
    File file = new File(fileName);

    try {
        try (PrintWriter output = new PrintWriter(new FileWriter(file))) {
          output.println(content);
          output.println();
          output.println("End of writing");
        }
        System.out.println("File been written successfully");
    } catch (IOException ex) {
      ex.printStackTrace(System.out);
    }
}

上面的代码没什么问题,我根本看不到嵌套try没有定义内部catch块的意义。还是我错过了这样做的目的?

修改后的代码:

public void writeFile(String fileName, String content){
    File file = new File(fileName);

    try (PrintWriter output = new PrintWriter(new FileWriter(file))) {
        output.println(content);
        output.println();
        output.println("End of writing");
        System.out.println("File been written successfully");
    } catch (IOException ex) {
      ex.printStackTrace(System.out);
    }
}

1 个答案:

答案 0 :(得分:4)

内部尝试是一种try-with-resources:

try (PrintWriter output = new PrintWriter(new FileWriter(file)))

这意味着它管理资源-PrintWriter-在尝试中的每个语句执行之后打开它并关闭它。外部尝试用于捕获错误。

Petter Friberg提出的修改后的代码是等效的。