New/strange Java “try()” syntax?

后端 未结 8 513
一个人的身影
一个人的身影 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: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.

提交回复
热议问题