-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathNestedException.java
80 lines (73 loc) · 1.78 KB
/
NestedException.java
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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
package exceptionsAndAssertions;
import java.io.FileReader;
import java.io.IOException;
/**
*
* @author chengfeili
* Jun 10, 2017 8:04:26 AM
*
*/
public class NestedException {
public void test() {
FileReader reader = null;
try {
reader = read();
} catch (IOException e) {
try {
if (reader != null)
reader.close();
} catch (IOException inner) {
}
}
}
private FileReader read() throws IOException {
// CODE GOES HERE
return null;
}
/**
* Line 46 throws an exception, which is caught on line 47. The catch block
* then throws an exception on line 48. If there were no finally block, the
* exception from line 48 would be thrown. However, the finally block runs
* after the try block.
*
* Since the finally block throws an exception of its own on line 50, this
* one gets thrown. The exception from the catch block gets forgotten about.
* This is why you often see another try / catch inside a finally block—to
* make sure it doesn’t mask the exception from the catch block.
*
*/
public void mask() throws Exception {
try {
throw new RuntimeException();
} catch (RuntimeException e) {
throw new RuntimeException();
} finally {
throw new Exception();
}
}
public String exceptions() {
String result = "";
String v = null;
try {
try {
result += "before ";
v.length();
result += "after ";
} catch (NullPointerException e) {
result += "catch ";
throw new RuntimeException();
} finally {
result += "finally ";
throw new Exception();
}
} catch (Exception e) {
result += "done ";
}
return result;
}
public static void main(String[] args) {
NestedException ne = new NestedException();
ne.test();
System.out.println(ne.exceptions()); // before catch finally done
}
}