try catch in Java 中的圆括号/圆括号()是什么
What is Round brackets / parentheses () in try catch in Java
据我所知,我们使用 try catch
如下:
try {
//Some code that may generate exception
}
catch(Exception ex) {
}
//handle exception
finally {
//close any open resources etc.
}
但在我发现的代码中
try(
ByteArrayOutputStream byteArrayStreamResponse = new ByteArrayOutputStream();
HSLFSlideShow pptSlideShow = new HSLFSlideShow(
new HSLFSlideShowImpl(
Thread.currentThread().getContextClassLoader()
.getResourceAsStream(Constants.PPT_TEMPLATE_FILE_NAME)
));
){
}
catch (Exception ex) {
//handel exception
}
finally {
//close any open resource
}
我试了下还是不明白为什么这个括号()
。
它的用途是什么?它是 Java 1.7 中的新功能吗?我可以在那里写什么样的语法?
还请给我一些API文档。
尝试使用 java 1.7 中新增的 Resources 语法。它用于声明所有可以关闭的资源。这是官方文档的link。
https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html
static String readFirstLineFromFile(String path) throws IOException {
try (BufferedReader br =
new BufferedReader(new FileReader(path))) {
return br.readLine();
}
}
In this example, the resource declared in the try-with-resources statement is a BufferedReader. The declaration statement appears within parentheses immediately after the try keyword. The class BufferedReader, in Java SE 7 and later, implements the interface java.lang.AutoCloseable. Because the BufferedReader instance is declared in a try-with-resource statement, it will be closed regardless of whether the try statement completes normally or abruptly (as a result of the method BufferedReader.readLine throwing an IOException).
据我所知,我们使用 try catch
如下:
try {
//Some code that may generate exception
}
catch(Exception ex) {
}
//handle exception
finally {
//close any open resources etc.
}
但在我发现的代码中
try(
ByteArrayOutputStream byteArrayStreamResponse = new ByteArrayOutputStream();
HSLFSlideShow pptSlideShow = new HSLFSlideShow(
new HSLFSlideShowImpl(
Thread.currentThread().getContextClassLoader()
.getResourceAsStream(Constants.PPT_TEMPLATE_FILE_NAME)
));
){
}
catch (Exception ex) {
//handel exception
}
finally {
//close any open resource
}
我试了下还是不明白为什么这个括号()
。
它的用途是什么?它是 Java 1.7 中的新功能吗?我可以在那里写什么样的语法?
还请给我一些API文档。
尝试使用 java 1.7 中新增的 Resources 语法。它用于声明所有可以关闭的资源。这是官方文档的link。 https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html
static String readFirstLineFromFile(String path) throws IOException {
try (BufferedReader br =
new BufferedReader(new FileReader(path))) {
return br.readLine();
}
}
In this example, the resource declared in the try-with-resources statement is a BufferedReader. The declaration statement appears within parentheses immediately after the try keyword. The class BufferedReader, in Java SE 7 and later, implements the interface java.lang.AutoCloseable. Because the BufferedReader instance is declared in a try-with-resource statement, it will be closed regardless of whether the try statement completes normally or abruptly (as a result of the method BufferedReader.readLine throwing an IOException).