Java SE 8 Programmer II — Question 43
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 () < 6) {
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. AgeOutOfLimitException is thrown.
- B. An UserException is thrown.
- C. A main method.
- D. A compilation error occurs in the
Correct answer: A
Explanation
The code will throw an AgeOutOfLimitException because the age provided (60) meets the condition for throwing that exception. The first condition checks the length of the name, which is valid, so it proceeds to check the age, resulting in the exception being thrown. Therefore, option A is correct, while the others do not describe the output accurately.