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」。
