0

I would like to use try-with-resources. I have two resources, where second depend on first. After initialize first, I need to execute method on first resources. Next I can initialize second resource. What can I do it?

try (First first = resource.get());
     --Here I need run method: first.connect(...);
     Second second = first.get())
     {
      ...
     }
user11149927
  • 23
  • 1
  • 5
  • 1
    Hope this will give an idea. https://stackoverflow.com/questions/47175526/try-with-multiple-resource-in-java/47175609 – Mebin Joe Mar 21 '19 at 11:25
  • 3
    Use a second try-with-resources inside the try block of the first try-with-resources. – JB Nizet Mar 21 '19 at 11:27

1 Answers1

2

You can nest try-with-resources, just like you can with normal try-blocks:

try (First first = resource.get()) {
    first.connect(...);
    try (Second second = first.get()) {
        // ...
    }
}
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
  • Thanks. I have: `try (First first = resource.get()) { first.connect(...); try (Second second = first.get()) { // ... } } catch(Exception ex){..}` When the second throw Exception, the first try-catch catch this exception? – user11149927 Mar 21 '19 at 11:47
  • @user11149927 of course, why do you think it wouldn't?! It is the first catch block that can handle the exception. – Mark Rotteveel Mar 21 '19 at 11:51