Sobes.tech
Junior — Middle

Will using close inside a try block have an effect?

sobes.tech AI

Answer from AI

If you call the close() method inside a try block, it will be executed, but if an exception occurs in the try block before the call to close(), this call may be skipped. Therefore, for proper resource cleanup, it is better to use the try-with-resources construct or call close() in the finally block.

Example with try-with-resources:

try (BufferedReader br = new BufferedReader(new FileReader("file.txt"))) {
    // work with br
} // br.close() will be called automatically

If you call close() inside a regular try, then if an exception occurs before the call to close(), the resource will not be closed, which can lead to resource leaks.

Will using close inside a try block have an effect… - sobes.tech