New/strange Java “try()” syntax?

后端 未结 8 507
一个人的身影
一个人的身影 2021-01-30 16:17

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\'
 */         


        
相关标签:
8条回答
  • 2021-01-30 16:32

    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.

    0 讨论(0)
  • 2021-01-30 16:39

    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.

    0 讨论(0)
  • 2021-01-30 16:40

    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

    0 讨论(0)
  • 2021-01-30 16:48

    This is Java 7's new try-with-resources statement: http://download.oracle.com/javase/7/docs/technotes/guides/language/try-with-resources.html

    0 讨论(0)
  • 2021-01-30 16:49

    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.

    0 讨论(0)
  • 2021-01-30 16:49

    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

    0 讨论(0)
提交回复
热议问题