java - Java中try catch中的圆括号/括号()是什么

标签 java try-catch parentheses

据我所知,我们使用 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 语法。它用于声明所有可以关闭的资源。这是官方文档的链接。 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).

关于java - Java中try catch中的圆括号/括号()是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37583464/

相关文章:

java - 如何从mysql数据库读取数据并将其插入到已实现的哈希表中?

java - 重复的属性值

php - 如何正确使用 Try-Catch Exception?

ios - 如何在新版本上转换 NSKeyedArchiver 对象

java - 快速、琐碎的 Java 问题 : Parenthesis around SQLException

c++ - 类实例化语法

python - Processing.py草图错误: unclosed paren/quote mark

java - C++ 与 Java 或 C# 中堆内存的回收方式有何区别

java - BufferedReader 和扫描仪 : limit the number of input characters

c# - 字典 ArgumentException 日志重复键 : which is more performant?