Sobes.tech
Senior

What is the purpose of the finally block? What is try-with-resources?

sobes.tech AI

Answer from AI

The finally block in Java is used to execute code that must run regardless of whether an exception was thrown or not, after the try block and any catch blocks. Typically, code for resource cleanup, such as closing files, database connections, etc., is placed in finally.

Example:

try {
    // code that might throw an exception
} catch (Exception e) {
    // exception handling
} finally {
    // code that always executes
}

try-with-resources is a construct introduced in Java 7 that simplifies working with resources implementing the AutoCloseable interface. It automatically closes resources after the try block, even if an exception occurs, reducing the risk of resource leaks.

Example of using try-with-resources:

try (BufferedReader br = new BufferedReader(new FileReader("file.txt"))) {
    String line = br.readLine();
    System.out.println(line);
} catch (IOException e) {
    e.printStackTrace();
}
// BufferedReader will automatically close after the try block

Thus, try-with-resources eliminates the need to explicitly close resources in a finally block.