What will be the output of the following program? class CustomException extends Exception {
What will be the output of the following program?
class CustomException extends Exception {
public CustomException(String message) {
super(message);
}
}
public class TestCustomException {
public static void main(String[] args) {
try {
validateAge(15);
} catch (CustomException e) {
System.out.println("Caught Exception: " + e.getMessage());
} finally {
System.out.println("Execution finished.");
}
}
public static void validateAge(int age) throws CustomException {
if (age < 18) {
throw new CustomException("Age must be 18 or above.");
}
System.out.println("Age is valid.");
}
}
Show answerHide answer
Correct answer: (D) Caught Exception: Age must be 18 or above. Execution finished.
Explanation
validateAge(15) throws CustomException with the message "Age must be 18 or above.", so "Age is valid." is never printed. The catch prints the message and the finally block prints "Execution finished.".