简体   繁体   English

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

[英]What is Round brackets / parentheses () in try catch in Java

As per as my knowledge we use try catch as follows:据我所知,我们使用try catch如下:

try {
   //Some code that may generate exception
}
catch(Exception ex) {
}
   //handle exception
finally {
   //close any open resources etc.
}

But in a code I found following但在我发现以下代码中

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
}

I am not able to understand why this parentheses () just after try.我不明白为什么这个括号()只是在尝试之后。

What is the usage of it?它的用途是什么? Is it new in Java 1.7?它是 Java 1.7 中的新功能吗? What kind of syntax I can write there?我可以在那里写什么样的语法?

Please also refer me some API documents.还请给我参考一些 API 文档。

It is try with Resources syntax which is new in java 1.7.尝试使用 java 1.7 中的新资源语法。 It is used to declare all resources which can be closed.它用于声明所有可以关闭的资源。 Here is the link to official documentation.这是官方文档的链接。 https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html 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.在这个例子中,在 try-with-resources 语句中声明的资源是一个 BufferedReader。 The declaration statement appears within parentheses immediately after the try keyword.声明语句紧跟在 try 关键字之后的括号内。 The class BufferedReader, in Java SE 7 and later, implements the interface java.lang.AutoCloseable. Java SE 7 及更高版本中的 BufferedReader 类实现了接口 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).因为 BufferedReader 实例是在 try-with-resource 语句中声明的,所以无论 try 语句是正常完成还是突然完成(作为 BufferedReader.readLine 方法抛出 IOException 的结果),它都会关闭。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM