GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • java.evolved
  • ←
  • →

This view

  • Original page
  • New address

GeezerVison is showing javaevolved.dev — Multi-catch exception handling | java.evolved

Home / Errors / Multi-catch exception handling
Errors Beginner

Multi-catch exception handling

  • 🐛 Report a code issue
  • 🌐 Report a translation issue
  • 💡 Suggest a new pattern

Catch multiple exception types in a single catch block.

Exception Handling
Code Comparison
✕ Pre-Java 7
try {
    process();
} catch (IOException e) {
    log(e);
} catch (SQLException e) {
    log(e);
} catch (ParseException e) {
    log(e);
}
✓ Java 7+
try {
    process();
} catch (IOException
    | SQLException
    | ParseException e) {
    log(e);
}
Share 𝕏
See a problem with this code? Let us know.
Why the modern way wins
📏

DRY

Same handling logic written once instead of three times.

🔄

Rethrowable

The caught exception can be rethrown with its precise type.

📖

Scannable

All handled types are visible in one place.

Old Approach
Separate Catch Blocks
Modern Approach
Multi-catch
Since JDK
7
Difficulty
Beginner
JDK Support
Multi-catch exception handling
Available

Widely available since JDK 7 (July 2011)

How it works

Multi-catch handles multiple exception types with the same code. The exception variable is effectively final, so you can rethrow it without wrapping.

Related Documentation
Catching and Handling Exceptions (dev.java) ↗
Proof
View proof source ↗
Related patterns
Errors Beginner

Null case in switch

Java 8
// Must check before switch
if (status == null) {
    return "unknown";
}
return switch (status) {
    case ACTIVE  -> "active";
    case PAUSED  -> "paused";
    default      -> "other";
};
Java 21+
return switch (status) {
    case null    -> "unknown";
    case ACTIVE  -> "active";
    case PAUSED  -> "paused";
    default      -> "other";
};
Hover to see modern ➜
JDK 21+ →
Errors Beginner

Helpful NullPointerExceptions

Java 8
// Old NPE message:
// "NullPointerException"
// at MyApp.main(MyApp.java:42)
// Which variable was null?!
Java 14+
// Modern NPE message:
// Cannot invoke "String.length()"
// because "user.address().city()"
// is null
// Exact variable identified!
Hover to see modern ➜
JDK 14+ →
Errors Beginner

Objects.requireNonNullElse()

Java 8
String name = input != null
    ? input
    : "default";
// easy to get the order wrong
Java 9+
String name = Objects
    .requireNonNullElse(
        input, "default"
    );
Hover to see modern ➜
JDK 9+ →
You are visitor 01402503 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.