【问题标题】:Is there any usage for nested try if without catch?如果没有捕获,嵌套尝试是否有任何用途?
【发布时间】:2019-09-05 01:48:41
【问题描述】:

从一本 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);
    }
}

【问题讨论】:

  • 内部try会自动关闭PrintWriter的资源,从jdk 9开始可以不用finally或者catch就可以try
  • @Deadpool:也就是说,在jdk 9之前,开发者通常要在finally块中手动关闭它?
  • 是的,完全是@Isaac,基本上你可以一次性完成所有这些,不需要内部
  • 我认为你可以使用内部捕获没有多大意义。

标签: java oop exception io try-catch


【解决方案1】:

内部try是一个try-with-resources:

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

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

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

【讨论】:

  • 你可以用一个内部的 catch 代替,我看不出有什么用处
  • @PetterFriberg 你的意思是finally?
  • 不只是内部捕获,相同的代码没有外部尝试捕获
  • “等价”不完全。在原始代码中,成功消息是在打印写入器关闭后写入的。在修改后的代码中,它是在关闭之前编写的。关闭时可能会发生异常。
  • @AndyTurner PrintWriter,因为 java 7 不会在 close() AFIK docs.oracle.com/javase/7/docs/api/java/io/… 上抛出 IOException,因此无论如何都不会被捕获
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-07-29
  • 2023-03-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-10
  • 1970-01-01
相关资源
最近更新 更多