While messing around with the custom formatting options in Eclipse, in one of the sample pieces of code, I saw code as follows:
/**
* \'try-with-resources\'
*/
The try-with-resources statement is a try statement that declares one or more resources. A resource is an object that must be closed after the program is finished with it. The try-with-resources statement ensures that each resource is closed at the end of the statement. Any object that implements java.lang.AutoCloseable, which includes all objects which implement java.io.Closeable, can be used as a resource.
Those are changes introduced in JDK7.
First statement is a try-with-resources. I don't know exactly why they exist but exceptions are often caused by inputstreams etc, I guess it just improves readability. Edit: thanks to the other answerers, I read the javadoc and I now know that it will close all i/o streams that implement AutoCloseable, omitting the need for a finally
block in a lot of situations
Second is a multi-catch, which is really handy when you have different exceptions that you handle in exactly the same way.
Same usage as using(Resource)
in C Sharp
,which means this resource will be automatic recycled when your program has leaven out of this code block.(Just my opinion)
The try-with-resources statement ensures that each resource is closed at the end of the statement. Any object that implements java.lang.AutoCloseable, which includes all objects which implement java.io.Closeable, can be used as a resource
The try-with-resources Statement
This is Java 7's new try-with-resources statement: http://download.oracle.com/javase/7/docs/technotes/guides/language/try-with-resources.html
It's called try-with-resource. It's a way so as to not have to clean after yourself as the language will do it for you.
it was added in java 7. It is called try with resources. Try with resources statement feature was introduced in java 7 version. Try with resource statement is a try statement that declares one or more statements. A resource is an object that must be closed after the program is finished with it.
Before java 7 we use finally block to close the resources that we have used in our program. In finally block we have to close all the resources manually that we have used in our program. For more information you can visit try with resources