What are parentheses / brackets () in try catch in Java

According to 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 the code I found after

 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 cannot understand why these are parentheses () right after the attempt.

What is its use? Is this new in Java 1.7? What syntax can I write there?

Please also call me some API docs.

+6
source share
1 answer

Try with resource syntax, which is new in java 1.7. It is used to declare all resources that may be closed. Here is a link to the 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 in parentheses immediately after the try keyword. The BufferedReader class, in Java SE 7 and later, implements the java.lang.AutoCloseable interface. Because the BufferedReader instance is declared in the try-with-resource statement, it will be closed regardless of whether the try statement completes normally or abruptly (as a result of the BufferedReader.readLine method, it throws an IOException).

+13
source

All Articles