Given the following code for the classes MyException and Test:
public class MyException extends RuntimeException{
}
public class Test {
public static void main(String[] args) {
try {
method1();
} catch (MyException ne) {
System.out.print("A");
}
}
public static void method1() { // line n1
try {
throw Math.random() > 0.5 ? new MyException() : new RuntimeException();
} catch (RuntimeException re) {
System.out.print("B");
}
}
}
What is the result?
A.
A
B.
B
C.
Either A or B
D.
A B
E. A compile time error occurs at line n1
題解
MyException是RuntimeException的一種,因此第13行無論拋出MyException還是RuntimeException,都會在第14行被catch接住,而輸出「B」。