-
Notifications
You must be signed in to change notification settings - Fork 10
/
CallingMethodsThatThrowExceptions.java
93 lines (78 loc) · 2.02 KB
/
CallingMethodsThatThrowExceptions.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
81
82
83
84
85
86
87
88
89
90
91
92
93
package exceptionsAndAssertions;
/**
*
* @author chengfeili
* Jun 10, 2017 10:57:52 AM
*
*/
class checked extends Exception{
}
public class CallingMethodsThatThrowExceptions {
// checked is a checked exception.
// it must be handled or declared.
// method1: declare exception
/*
* public static void main(String[] args) throws checked {
eat();
}*/
// method2: handle exception
public static void main(String[] args) {
try {
eat();
} catch (checked e) {
System.out.println("handle");
}
// print an exception
try {
hop();
} catch (Exception e) {
System.out.println(e);
System.out.println(e.getMessage());
e.printStackTrace();
/*
* java.lang.RuntimeException: cannot hop
* cannot hop
* java.lang.RuntimeException: cannot hop
* at trycatch.Handling.hop(Handling.java:15)
* at trycatch.Handling.main(Handling.java:7)
*/
}
}
private static void hop() {
throw new RuntimeException("cannot hop");
}
private static void eat() throws checked {
}
/**
public void bad() {
try {
eatCarrot();
} catch (checked e) { // DOES NOT COMPILE
System.out.print("sad rabbit");
}
}
*/
public void good() throws checked {
eatCarrot();
}
private static void eatCarrot() {
}
/**
* Java knows that eatCarrot() can’t throw a checked exception—which means
* there’s no way for the catch block in bad() to be reached. In comparison,
* good() is free to declare other exceptions.
*/
// subclasses
/**
* When a class overrides a method from a superclass or implements a method
* from an interface, it’s not allowed to add new checked exceptions to the
* method signature
*
* A subclass is allowed to declare fewer exceptions than the superclass or
* interface. This is legal because callers are already handling them.
*
* declare new runtime exceptions in a subclass method is that the
* declaration is redundant. Methods are free to throw any runtime
* exceptions they want without mentioning them in the method declaration.
*/
}