Sobes.tech
Junior — Middle

Is it mandatory to use a catch block when working with try-with-resources?

sobes.tech AI

Answer from AI

No, the catch block is not mandatory when using try-with-resources. In a try-with-resources statement, you can omit catch if you just want to automatically close resources, and handle exceptions at a higher level or use a finally block. For example:

try (BufferedReader br = new BufferedReader(new FileReader("file.txt"))) {
    String line = br.readLine();
    System.out.println(line);
}
// No catch here, exceptions can be propagated further

However, if you need to handle exceptions directly, then a catch block is necessary.

Is it mandatory to use a catch block when working… - sobes.tech