关于 java 的 try/catch 语法;这些块是等价的吗?
Regarding java's try/catch syntax; are these blocks equivalent?
在以下区块中:
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 的这种语法,但我不太确定如何使用它。如果我在这里能想到的唯一假设是不正确的,那么任何人都可以帮助我理解它或指出解释此语法的参考资料吗?我在这里用谷歌搜索了很多,但没能找到任何适用的东西,尽管我的搜索能力不是最好的。
提前致谢!
没有。第一个是 try with resources,这不是一个直观的名称。当您需要使用资源然后关闭它时使用它。它使您不必每次都手动关闭它们,并有效地将资源范围限制在花括号内。
后一个不一样:资源 fis
在 try/catch 块退出后仍将打开。 try-with-resources
的引入是为了解决这个问题。
在以下区块中:
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 的这种语法,但我不太确定如何使用它。如果我在这里能想到的唯一假设是不正确的,那么任何人都可以帮助我理解它或指出解释此语法的参考资料吗?我在这里用谷歌搜索了很多,但没能找到任何适用的东西,尽管我的搜索能力不是最好的。
提前致谢!
没有。第一个是 try with resources,这不是一个直观的名称。当您需要使用资源然后关闭它时使用它。它使您不必每次都手动关闭它们,并有效地将资源范围限制在花括号内。
后一个不一样:资源 fis
在 try/catch 块退出后仍将打开。 try-with-resources
的引入是为了解决这个问题。