Skip to content

Commit a12da0b

Browse files
author
Yalun Qin
committed
Add more examples to Checked and Unchecked Exception tests
1 parent d099d12 commit a12da0b

2 files changed

Lines changed: 26 additions & 2 deletions

File tree

CheckedExceptionTest.java

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,16 @@ private static byte[] toByteArray(Animal animal) {
2323
// If this function throws checked exceptions, they must be caught by the caller
2424
// of this function, or explicitly thrown out again.
2525
private static byte[] toByteArray2(Animal animal) throws InvalidClassException,
26-
NotSerializableException, IOException {
26+
NotSerializableException, IOException {
27+
28+
//Set checkOtherExceptions to true to see if this method can throw exceptions other than
29+
//those declared in the signature -- the answer is YES!
30+
//RuntimeException inherits directly from Exception, and so does IOException, which is the
31+
//superclass of InvalidClassException and NotSerializableException
32+
boolean checkOtherExceptions = false;
33+
if (checkOtherExceptions) {
34+
throw new RuntimeException("RuntimeException in toByteArray2, not in the function signature");
35+
}
2736
byte[] animalBytes = null;
2837

2938
ByteArrayOutputStream bos = new ByteArrayOutputStream();

UncheckedExceptionTest.java

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,20 @@ private static Person invokeGetAnimalOwner(Animal animal) {
2828

2929
}
3030

31+
private static String testAfterFinally() {
32+
String str = "";
33+
try {
34+
throw new RuntimeException("Throwed an exception inside try!");
35+
} finally {
36+
System.out.println("Statements inside finally");
37+
str = "Finally";
38+
}
39+
/* This part won't be reached! It's a compilation error if you uncomment it.
40+
System.out.println("Statements after finally!");
41+
return str;
42+
*/
43+
}
44+
3145
public static void main(String[] args) {
3246
Animal animal = null;
3347
try {
@@ -37,6 +51,7 @@ public static void main(String[] args) {
3751
System.out.println("This statement should only be executed when " +
3852
"invokeGetAnimalOwner doesn't caught the execption");
3953
}
40-
54+
String testStr = testAfterFinally();
55+
System.out.println("testStr = " + testStr);
4156
}
4257
}

0 commit comments

Comments
 (0)