【问题标题】:Regarding java's try/catch syntax; are these blocks equivalent? [duplicate]关于 java 的 try/catch 语法;这些块是等效的吗? [复制]
【发布时间】:2018-02-08 02:12:31
【问题描述】:

在以下块中:

    try (final InputStream fis = new BufferedInputStream(Files.newInputStream(f.toPath()));
            final ArchiveInputStream ais = factory.createArchiveInputStream(fn, fis)) {
        System.out.println("Created " + ais.toString());
        ArchiveEntry ae;
        while ((ae = ais.getNextEntry()) != null) {
            System.out.println(ae.getName());
        }
    }

这是否等同于以下块:

try {
    final InputStream fis = new BufferedInputStream(Files.newInputS...;
} catch {
    System.out.println("Created " + ais.toString());...
}

我在 apache common 的库中偶然发现了 try/catch 的这种语法,但我不确定如何使用它。如果我在这里能想到的唯一假设不正确,任何人都可以帮助我理解它或将我指向解释此语法的参考吗?我在这里用谷歌搜索和搜索了很多,但找不到任何适用的东西,尽管我的 search-fu 不是最好的。

提前致谢!

【问题讨论】:

标签: java syntax coding-style try-catch


【解决方案1】:

没有。首先是尝试使用资源,这不是一个直观的名称。当您需要使用资源然后关闭它时使用它。它使您不必每次都手动关闭它们,并有效地将资源的范围限制在花括号内。

后者不一样:资源fis 在try/catch 块退出后仍将打开。引入try-with-resources 来解决此问题。

【讨论】:

  • 请解释一下您的意思:“退出try/catch块后资源fis仍将存在”。
  • 文件阅读器等资源使用完毕后需要关闭。在第一个块中,资源 fis 在 try/catch 块完成后关闭,但在第二种情况下,它必须手动关闭
  • 然后说它在try/catch块之后仍然保持打开状态。 “resource fis will still exist”没有多大意义。
猜你喜欢
  • 1970-01-01
  • 2011-01-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-03-28
  • 2011-04-15
  • 2017-06-11
  • 1970-01-01
相关资源
最近更新 更多