Try with resource is the short form of try block and finally block. It will close all the resources automatically when try block is done.
Example:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class TryWithResourcesExample {
public static void main(String[] args) {
String filePath = “example.txt”;
// Try-with-resources block
try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {
String line;
// Read file line by line
while ((line = br.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
// Handle potential IOException
System.out.println(“Error reading file: ” + e.getMessage());
}
System.out.println(“Program continues normally…”);
}
}