Given the code fragments:
void doStuff() throws ArithmeticException, NumberFormatException, Exception {
if (Math.random() > -1) throw new Exception ("Try again");
}
and
try {
doStuff();
} catch (ArithmeticException | NumberFormatException | Exception e) {
System.out.println(e.getMessage());
} catch (Exception e) {
System.out.println(e.getMessage());
}
Which modification enables the code to print Try again?
A. Comment the lines 28, 29 and 30.
B. Replace line 26 with:
} catch (Exception | ArithmeticException | NumberFormatException e) {
C. Replace line 26 with:
} catch (ArithmeticException | NumberFormatException e) {
D. Replace line 27 with:
throw e;
題解
題目原先提供的程式會在第 26 行和第 28 行編譯錯誤。
第 26 行錯誤的原因在於,ArithmeticException 和 NumberFormatException 均為 Exception 的子類別,重複包含了。
第 28 行錯誤的原因在於,第 26 行已經有 catch 到 Exception 了,所以永遠執行不到第 28 行。
要修正這個問題,可以把第 26 行的 Exception 拿掉,因此答案是選項 C。
