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

JavaTry CatchParentheses

Java Problem Overview


As per as my knowledge we use try catch as follows:

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? What kind of syntax I can write there?

Please also refer me some API documents.

Java Solutions


Solution 1 - Java

It is try with Resources syntax which is new in 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

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).

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionPartha Sarathi GhoshView Question on Stackoverflow
Solution 1 - JavaPrasad KharkarView Answer on Stackoverflow