Bird
0
0

Which of the following code snippets correctly defines and throws this exception inside a method validateAge?

hard📝 Application Q15 of 15
Java - Custom Exceptions
You want to create a checked custom exception InvalidAgeException that should be thrown when age is less than 18. Which of the following code snippets correctly defines and throws this exception inside a method validateAge?
Aclass InvalidAgeException extends Exception { public InvalidAgeException() {} } void validateAge(int age) { if (age < 18) throw new InvalidAgeException(); }
Bclass InvalidAgeException { public InvalidAgeException(String msg) { super(msg); } } void validateAge(int age) { if (age < 18) throw new InvalidAgeException("Age must be 18 or older"); }
Cclass InvalidAgeException extends RuntimeException { public InvalidAgeException() {} } void validateAge(int age) { if (age < 18) throw new InvalidAgeException(); }
Dclass InvalidAgeException extends Exception { public InvalidAgeException(String msg) { super(msg); } } void validateAge(int age) throws InvalidAgeException { if (age < 18) throw new InvalidAgeException("Age must be 18 or older"); }
Step-by-Step Solution
Solution:
  1. Step 1: Define a checked exception with message constructor

    class InvalidAgeException extends Exception { public InvalidAgeException(String msg) { super(msg); } } void validateAge(int age) throws InvalidAgeException { if (age < 18) throw new InvalidAgeException("Age must be 18 or older"); } correctly extends Exception and defines a constructor that accepts a message, calling super(msg).
  2. Step 2: Throw exception with message and declare it

    The method validateAge throws InvalidAgeException when age < 18 and declares it with throws InvalidAgeException.
  3. Final Answer:

    class InvalidAgeException extends Exception { public InvalidAgeException(String msg) { super(msg); } } void validateAge(int age) throws InvalidAgeException { if (age < 18) throw new InvalidAgeException("Age must be 18 or older"); } -> Option D
  4. Quick Check:

    Checked exception needs constructor, throw, and throws declaration [OK]
Quick Trick: Checked exceptions need constructor, throw, and throws declaration [OK]
Common Mistakes:
  • Not extending Exception for checked exceptions
  • Missing throws declaration in method
  • Not calling super(message) in constructor

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Java Quizzes