View the exhibit.

class MissingInfoException extends Exception {
}

class AgeOutofRangeException extends Exception {
}

class Candidate {

    String name;
    int age;

    Candidate(String name, int age) throws Exception {
        if (name == null) {
            throw new MissingInfoException();
        } else if (age <= 10 || age >= 150) {
            throw new AgeOutofRangeException();
        } else {
            this.name = name;
            this.age = age;
        }
    }

    public String toString() {
        return name + " age: " + age;
    }
}

Given the code fragment:

public class Test {
    public static void main(String[] args) {
        Candidate c = new Candidate("James", 20);
        Candidate c1 = new Candidate("Williams", 32);
        System.out.println(c);
        System.out.println(c1);
    }
}

Which change enables the code to print the following?

James age: 20
Williams age: 32

A.
Replacing line 5 with

public static void main (String [] args) throws MissingInfoException, AgeOutofRangeException {
B.
Replacing line 5 with
public static void main (String [] args) throws.Exception {
C.
Enclosing line 6 and line 7 within a try block and adding:
catch (MissingInfoException e1) { //code goes here
}
catch (AgeOutofRangeException e2) {//code goes here
}
catch(Exception e3) { //code goes here
}
D.
Enclosing line 6 and line 7 within a try block and adding:
catch (MissingInfoException e2) { //code goes here
}
catch (AgeOutofRangeException e3) {//code goes here
}

題解

原本題目提供的程式會在第 6 行和第 7 行出現編譯錯誤,原因在於 Candidate 的物件有拋出 Exception。由於 Exception 是需要檢查的例外(checked exception),因此必須要撰寫程式去處理它。

選項 A,只讓 main 方法拋出 MissingInfoException 和 AgeOutofRangeException 是不夠的,必須要拋出 Exception 才行。

選項 B,throws 的用法錯誤。

選項 C,有 catch 到 Exception,正確選項。

選項 D,只讓 try-catch 接住 MissingInfoException 和 AgeOutofRangeException 是不夠的,必須要接住 Exception 才行。