Java

Multi-Catch + Exception Chaining

admin by @admin ADMIN
3d ago
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
Catch several unrelated exception types in one block with `|`. Re-throw with `cause` to preserve the stack trace and underlying error.
Java
Raw
import java.io.*;
import java.sql.*;

class Demo {
    void multiCatch() {
        try {
            // ... code that might throw IOException or SQLException ...
        } catch (IOException | SQLException e) {
            System.err.println("transient error: " + e.getMessage());
        }
    }

    // Wrap & re-throw with the original as cause
    void wrap() throws AppException {
        try {
            Files.newBufferedReader(Path.of("config.toml"));
        } catch (IOException e) {
            throw new AppException("config load failed", e);   // preserves stack
        }
    }

    // getCause() walks the chain
    void inspect(Throwable t) {
        for (var cur = t; cur != null; cur = cur.getCause()) {
            System.out.println("→ " + cur);
        }
    }
}
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.