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和line n3會因為沒有處理Exception而發生編譯錯誤。