forked from eaglesky/JavaPractice
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathUncheckedExceptionTest.java
More file actions
57 lines (52 loc) · 1.68 KB
/
UncheckedExceptionTest.java
File metadata and controls
57 lines (52 loc) · 1.68 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
55
56
57
// Design the code to throw NullPointerException at runtime.
// The code should be compiled successfully as there is no checked exception.
// NullPointerException should be thrown from getAnimalOwner and caught in
// invokeGetAnimalOwner.
public class UncheckedExceptionTest {
private static Person getAnimalOwner(Animal animal) {
try {
return animal.getOwner();
} finally {
System.out.println("getAnimalOwner clean up");
// Don't include 'return' in finally! Otherwise the uncaught execption will be lost!
//return null;
}
}
// Comment the try-catch block out if you want to see the propagation of execption
private static Person invokeGetAnimalOwner(Animal animal) {
try {
Person owner = getAnimalOwner(animal);
System.out.println("This should never be executed!");
return owner;
} catch (Exception e) {
e.printStackTrace();
System.out.println("Caught runtime exception!");
return null;
}
}
private static String testAfterFinally() {
String str = "";
try {
throw new RuntimeException("Throwed an exception inside try!");
} finally {
System.out.println("Statements inside finally");
str = "Finally";
}
/* This part won't be reached! It's a compilation error if you uncomment it.
System.out.println("Statements after finally!");
return str;
*/
}
public static void main(String[] args) {
Animal animal = null;
try {
Person owner = invokeGetAnimalOwner(animal);
} catch (Exception e) {
e.printStackTrace();
System.out.println("This statement should only be executed when " +
"invokeGetAnimalOwner doesn't caught the execption");
}
String testStr = testAfterFinally();
System.out.println("testStr = " + testStr);
}
}