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:
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).
Step 2: Throw exception with message and declare it
The method validateAge throws InvalidAgeException when age < 18 and declares it with throws InvalidAgeException.
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
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
Master "Custom Exceptions" in Java
9 interactive learning modes - each teaches the same concept differently