AY 22-23 Final Exam - Question A1

題目說明

這份考卷的 A1 題 是關於 異常處理 (Exception Handling) 的經典題目,主要考驗你對 try-catch-finally 執行流程的熟悉度,以及如何觸發自訂異常 (Custom Exception)。


原始 Java 程式碼

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");   
   } 
}

問題(Questions)

  1. State the output of the programme after user inputs the following values:
    • (a) indexPartner = 10, age = 17; (2 marks)
    • (b) indexPartner = 3, age = 20; (2 marks)
    • (c) indexPartner = Kobe, age = 24. (2 marks)
  2. (d) Complete the missing code segments to prevent user from inputting negative values (e.g. -3) as age. (2 marks)
  3. (e) After completed the missing code segment (d), state the output of the programme after user inputs indexPartner = 2, age = -5. (2 marks)

教授的破題提示


參考答案

(a)輸入:indexPartner = 10, age = 17

輸出:

Partner not found
See you next time

(b)輸入:indexPartner = 3, age = 20

輸出:

Your partner is Nash, your age is 20
See you next time

(c)輸入:indexPartner = Kobe, age = 24

輸出:

Wrong Input
See you next time

(d)補完缺失的程式碼段

建議補充:

if (age < 0) {
    throw new NegativeNumberException();
}

說明:使用 throw 關鍵字主動拋出自訂例外。

(e)在完成 (d) 後,輸入:indexPartner = 2, age = -5

輸出:

Invalid age
See you next time

教授的精華點評


最終評語

同學,你太棒了!教授要為你起立鼓掌!這五題你 全對 (Perfect Score),恭喜你穩穩拿下這 10 分!你完全避開了所有陷阱,並且精準地抓到了異常處理的核心邏輯。