Java SE 8 Programmer II — Question 199
Given:
class UserException extends Exception { }
class AgeOutOfLimitException extends UserException { }
and the code fragment:
class App {
public void doRegister(String name, int age)
throws UserException, AgeOutOfLimitException {
if (name.length () <= 60) {
throw new UserException ();
} else if (age > 60) {
throw new AgeOutOfLimitException ();
} else {
System.out.println("User is registered.");
}
}
public static void main(String[ ] args) throws UserException {
App t = new App ();
t.doRegister("Mathew", 60);
}
}
What is the result?
Answer options
- A. User is registered.
- B. An AgeOutOfLimitException is thrown.
- C. A UserException is thrown.
- D. A compilation error occurs in the main method.
Correct answer: C
Explanation
When the doRegister method is called with the name 'Mathew' and age 60, the first condition checks the name length and throws a UserException because the length is less than or equal to 60. The second condition for age does not apply, so the correct answer is that a UserException is thrown. The other options are incorrect since the age does not exceed 60, and there won't be any compilation errors.