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。
