GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing javaevolved.dev — Multi-catch exception handling | java.evolved
Errors
Beginner
Multi-catch exception handlingCatch multiple exception types in a single catch block. 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);
}
See a problem with this code? Let us know.
Why the modern way wins
📏
DRYSame handling logic written once instead of three times. 🔄
RethrowableThe caught exception can be rethrown with its precise type. 📖
ScannableAll 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
Proof
Related patterns
Errors
Beginner
Null case in switchJava 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";
};
JDK 21+
→
Errors
Beginner
Helpful NullPointerExceptionsJava 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!
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"
);
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. |