-1

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 final 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 final block?

João Dias
  • 16,277
  • 6
  • 33
  • 45
rasilvap
  • 1,771
  • 3
  • 31
  • 70

2 Answers2

1

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

Yu Cheng
  • 131
  • 1
  • 3
  • The object is from a library, do you mean I have to create a wrapper which inherit from DockerClient and implement closeable? or something similar? – rasilvap Oct 05 '21 at 18:23
  • You can do that, but I suggest you simply use the old try-catch-finally block as shown in my edited answer. – Yu Cheng Oct 05 '21 at 18:26
1

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.

iggi
  • 145
  • 1
  • 7