Home > other >  Close a resource in a Finally block from a try catch with resources
Close a resource in a Finally block from a try catch with resources

Time:10-06

Hi I have in my code the next:

    try (DockerClient client
                 = 
   DefaultDockerClient.fromEnv().connectTimeoutMillis(TimeUnit.SECONDS.toMillis(3)).build()) {
         //some code here
        }catch (DockerCertificateException e) {
              log.warn("Failed to connect Docker Client {}", e.getMessage());
       }
       finally {
        
      }

I need to close the client in the finally block, but I can't because I'm getting an error (Cannot resolve symbol client).

Is there any way to close this client in the finally bock?

CodePudding user response:

The object in try(...) must implement AutoClosable and that object will be automatically closed whether or not an exception happens. You don't need the finally block at all.

If the object does not implement AutoClosable, you can fall back to the old try-catch-finally block as

DockerClient client = null;
try {
  //some code here
  client = DefaultDockerClient.fromEnv().connectTimeoutMillis(TimeUnit.SECONDS.toMillis(3)).build();
} catch (DockerCertificateException e) {
  log.warn("Failed to connect Docker Client {}", e.getMessage());
} finally {
  if (client != null) client.close();        
}

This is called the Java try-with-resources block. You can see an example that compares normal try-catch-finally block with the try-with-resources block here: https://www.baeldung.com/java-try-with-resources#replacing

CodePudding user response:

Client will be closed, cause you are using try-with-resources (when you open resourse in try(resource definition)), which closes resource after try block automatically, you don`t need to write finally block.

  • Related