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
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 才行。
