Given the code fragment:
public class Test {
void readCard() throws Exception {
System.out.println("Reading Card");
}
void checkCard(int carNo) throws Exception {
System.out.println("Checking Card");
}
public static void main(String[] args) throws RuntimeException { // line n1
Test ex = new Test();
int carNo = 12344;
ex.checkCard(carNo); // line n2
ex.readCard(carNo); // line n3
}
}
What is the result?
A.
Reading Card
Checking Card
Checking Card
B. Compilation fails only at line n1.
C. Compilation fails only at line n2.
D. Compilation fails only at line n3.
E. Compilation fails at both line n2 and line n3.
题解
「checkCard」方法使用 throws 关键字来将 Exception 抛出,Exception 是属于 checked exception,因此在「main」方法中必须要撰写程序来处理「checkCard」方法所抛出的 Exception。「main」方法虽然有用 throws 将 RuntimeException 抛出,但是 Exception 并不是 RuntimeException(Exception 不是继承 RuntimeException),因此这题 line n2 会因为没有处理 Exception 而发生编译错误。line n3 所调用的「readCard」方法同样会抛出 Exception,而且它并没有定义参数,调用时却传入了一个 int 参数,所以 line n3 也会发生编译错误(实际编译时,编译器会先回报 line n3 的参数错误,把它修正之后才会看到没有处理 Exception 的错误)。
