-
Notifications
You must be signed in to change notification settings - Fork 25
Expand file tree
/
Copy pathmulti-catch.yaml
More file actions
54 lines (54 loc) · 1.42 KB
/
Copy pathmulti-catch.yaml
File metadata and controls
54 lines (54 loc) · 1.42 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
---
id: 67
slug: "multi-catch"
title: "Multi-catch exception handling"
category: "errors"
difficulty: "beginner"
jdkVersion: "7"
oldLabel: "Pre-Java 7"
modernLabel: "Java 7+"
oldApproach: "Separate Catch Blocks"
modernApproach: "Multi-catch"
oldCode: |-
try {
process();
} catch (IOException e) {
log(e);
} catch (SQLException e) {
log(e);
} catch (ParseException e) {
log(e);
}
modernCode: |-
try {
process();
} catch (IOException
| SQLException
| ParseException e) {
log(e);
}
summary: "Catch multiple exception types in a single catch block."
explanation: "Multi-catch handles multiple exception types with the same code. The\
\ exception variable is effectively final, so you can rethrow it without wrapping."
whyModernWins:
- icon: "📏"
title: "DRY"
desc: "Same handling logic written once instead of three times."
- icon: "🔄"
title: "Rethrowable"
desc: "The caught exception can be rethrown with its precise type."
- icon: "📖"
title: "Scannable"
desc: "All handled types are visible in one place."
support:
state: "available"
description: "Widely available since JDK 7 (July 2011)"
prev: "errors/require-nonnull-else"
next: "errors/null-in-switch"
related:
- "errors/null-in-switch"
- "errors/helpful-npe"
- "errors/require-nonnull-else"
docs:
- title: "Catching and Handling Exceptions (dev.java)"
href: "https://dev.java/learn/exceptions/catching-handling/"