R
Rishtaara
Java Fundamentals
Lesson 25 of 36Article16 min

Multiple Exceptions & try-with-resources

Use multiple catch blocks or one catch with types separated by | : catch (IOException | SQLException e).

Multiple Exceptions — catch several types

Use multiple catch blocks or one catch with types separated by | : catch (IOException | SQLException e).

Order catches from specific to general — IOException before Exception.

Real-life example: One fire drill handles smoke (IOException) and power cut (SQLException) — different fixes for each alarm.

Multi-catch
try {
    String s = null;
    System.out.println(s.length());
} catch (NullPointerException | ArrayIndexOutOfBoundsException e) {
    System.out.println("Bad access: " + e.getMessage());
}

try-with-resources — auto-close

try (Resource r = ...) { } closes resources automatically — files, streams, connections.

Resource must implement AutoCloseable. Cleaner than manual finally close.

Real-life example: try-with-resources is a library that lends you a book and takes it back when you leave — no forgotten returns.

try-with-resources
import java.io.*;

try (FileWriter writer = new FileWriter("notes.txt")) {
    writer.write("Hello, Rishtaara!");
} catch (IOException e) {
    System.out.println("Write failed: " + e.getMessage());
}
// writer closed automatically