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) { |
} catch (ArithmeticException | NumberFormatException e) { |
throw e; |
題解
題目原先提供的程式會在第26行和第28行編譯錯誤。
第26行錯誤的原因在於,ArithmeticException和NumberFormatException均為Exception的子類別,重複包含了。
第28行錯誤的原因在於,第26行已經有catch到Exception了,所以永遠執行不到第26行。
要修正這個問題,可以把第26行的Exception拿掉,因此答案是選項C。