🏷 Exception Handling
4 patterns
Topic: Exception Handling
All Java patterns related to Exception Handling — java.evolved
I/O
Try-with-resources improvement
Old
Connection conn = getConnection();
// Must re-declare in try
try (Connection c = conn) {
use(c);
}
Modern
Connection conn = getConnection();
// Use existing variable directly
try (conn) {
use(conn);
}
hover to see modern →
JDK 9+
learn more →
Errors
Helpful NullPointerExceptions
Old
// Old NPE message:
// "NullPointerException"
// at MyApp.main(MyApp.java:42)
// Which variable was null?!
Modern
// Modern NPE message:
// Cannot invoke "String.length()"
// because "user.address().city()"
// is null
// Exact variable identified!
hover to see modern →
JDK 14+
learn more →
Errors
Multi-catch exception handling
Old
try {
process();
} catch (IOException e) {
log(e);
} catch (SQLException e) {
log(e);
} catch (ParseException e) {
log(e);
}
Modern
try {
process();
} catch (IOException
| SQLException
| ParseException e) {
log(e);
}
hover to see modern →
JDK 7+
learn more →
Errors
Optional.orElseThrow() without supplier
Old
// Risky: get() throws if empty, no clear intent
String value = optional.get();
// Verbose: supplier just for NoSuchElementException
String value = optional
.orElseThrow(NoSuchElementException::new);
Modern
// Clear intent: throws NoSuchElementException if empty
String value = optional.orElseThrow();
hover to see modern →
JDK 10+
learn more →