Understanding the try-with-resources Statement

Asked 2 years ago, Updated 2 years ago, 32 views

This is a question about the java try-with-resources statement.

If I declare an object outside the parentheses of try() as shown below, will it result in a compilation error?

MyResource obj1;
try(obj1 = new MyResource("obj1")}
    // processing
} catch(SQLExceptione){
   // exception handling
}

java

2022-09-30 17:49

1 Answers

Yes, compile error.

As found in the document ,

The try-with-resources statement is a try statement that declares one or more resources.

However, in a newer version of Java, you can also write in the same way as you can find on this page.


2022-09-30 17:49

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.