-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathCheckedExceptionTest.java
More file actions
63 lines (52 loc) · 2.11 KB
/
CheckedExceptionTest.java
File metadata and controls
63 lines (52 loc) · 2.11 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
58
59
60
61
62
63
import java.io.*;
public class CheckedExceptionTest {
// Remove the try..catch block to see unreported error during compiling.
// out.writeObject function throws some checked exceptions that must be
// either caught or explicitly thrown out(toByteArray2). Failing to do this
// will cause compiling error: unreported exception...
private static byte[] toByteArray(Animal animal) {
byte[] animalBytes = null;
try {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream out = new ObjectOutputStream(bos);
out.writeObject(animal);
animalBytes = bos.toByteArray();
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("toByteArray ends");
return animalBytes;
}
// If this function throws checked exceptions, they must be caught by the caller
// of this function, or explicitly thrown out again.
private static byte[] toByteArray2(Animal animal) throws InvalidClassException,
NotSerializableException, IOException {
//Set checkOtherExceptions to true to see if this method can throw exceptions other than
//those declared in the signature -- the answer is YES!
//RuntimeException inherits directly from Exception, and so does IOException, which is the
//superclass of InvalidClassException and NotSerializableException
boolean checkOtherExceptions = false;
if (checkOtherExceptions) {
throw new RuntimeException("RuntimeException in toByteArray2, not in the function signature");
}
byte[] animalBytes = null;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream out = new ObjectOutputStream(bos);
out.writeObject(animal);
animalBytes = bos.toByteArray();
System.out.println("toByteArray2 ends");
return animalBytes;
}
public static void main(String[] args) {
Animal animal = new Animal(10, 30);
// Uncomment the following code to see the NotSerializableException
//animal.setOwner(new Person("Yalun", 25));
byte[] animalBytes = toByteArray(animal);
try {
byte[] animalBytes2 = toByteArray2(animal);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("CheckedExceptionTest ends");
}
}