這份考卷的 A1 題 是關於 異常處理 (Exception Handling) 的經典題目,主要考驗你對 try-catch-finally 執行流程的熟悉度,以及如何觸發自訂異常 (Custom Exception)。
import java.util.*;
public class ChoosePartner {
public static void main(String [ ] args) {
Scanner sc = new Scanner(System.in);
String [] arrayPartner = { "Kobe", "James", "Kevin", "Nash", "Rain" };
System.out.print("Which person you will choose to be your partner?");
try {
int indexPartner = sc.nextInt();
System.out.print("What is your age?");
int age = sc.nextInt();
/* missing code segment (d) */
System.out.println("Your partner is " + arrayPartner[indexPartner] +
" ,your age is " + age);
} catch (InputMismatchException e) {
System.out.println("Wrong Input");
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Partner not found");
} catch (NegativeNumberException e){
System.out.println(e.getMessage());
} catch (Exception e){
System.out.println("Some Exception catched");
} finally {
System.out.println("See you next time");
}
}
}
public class NegativeNumberException extends ArithmeticException{
public NegativeNumberException(){
super("Invalid age");
}
}
arrayPartner 的長度只有 5,輸入 10 會發生什麼事?indexPartner 是一個 int 整數,但使用者輸入了字串 "Kobe",這會觸發哪一種 Exception?NegativeNumberException?需要用到哪個關鍵字 (Keyword)?e.getMessage() 會印出什麼字串?(去看看 NegativeNumberException 的 Constructor 裡面寫了什麼)。輸出:
Partner not found
See you next time
輸出:
Your partner is Nash, your age is 20
See you next time
輸出:
Wrong Input
See you next time
建議補充:
if (age < 0) {
throw new NegativeNumberException();
}
說明:使用 throw 關鍵字主動拋出自訂例外。
輸出:
Invalid age
See you next time
catch 區塊:陣列越界觸發 ArrayIndexOutOfBoundsException;型態輸入錯誤觸發 InputMismatchException。finally 一定會執行,因此每題都會印出 See you next time。throw new NegativeNumberException(); 來主動觸發自訂例外(注意不是方法簽章的 throws)。NegativeNumberException 後,e.getMessage() 會回傳建構子中傳給 super 的字串:Invalid age。同學,你太棒了!教授要為你起立鼓掌!這五題你 全對 (Perfect Score),恭喜你穩穩拿下這 10 分!你完全避開了所有陷阱,並且精準地抓到了異常處理的核心邏輯。