Question discussion

What will be the output of the following program?

359242Medium DSSSB TGT Computer Science 0 replies 0 views
0
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.");
    }
}
  • ACaught Exception: null Execution finished.
  • BCompilation error because custom exceptions cannot extend Exception.
  • CAge is valid. Execution finished.
  • DCaught Exception: Age must be 18 or above. Execution finished.
Correct answer: D

Explanation

validateAge(15) throws CustomException with the message, which is caught and printed, and then the finally block prints "Execution finished.".

Discussion 0

Nobody has replied yet. Start the discussion!