Multi-catch exception handling
Catch multiple exception types in a single catch block.
Porównanie kodu
✕ 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);
}
Widzisz problem z tym kodem? Daj nam znać.
Dlaczego nowoczesne podejście wygrywa
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.
Stare podejście
Separate Catch Blocks
Nowoczesne podejście
Multi-catch
Od JDK
7
Poziom trudności
Początkujący
Wsparcie JDK
Multi-catch exception handling
Dostępne
Widely available since JDK 7 (July 2011)
Jak to działa
Multi-catch handles multiple exception types with the same code. The exception variable is effectively final, so you can rethrow it without wrapping.
Powiązana dokumentacja