Bird
0
0

Consider this code snippet:

hard📝 Application Q9 of 15
Java - Custom Exceptions
Consider this code snippet:
class MyException extends Exception {
  public MyException(String msg) { super(msg); }
}
public class Main {
  static void validate(int age) throws MyException {
    if (age < 18) throw new MyException("Age must be 18 or older");
  }
  public static void main(String[] args) {
    try {
      validate(16);
    } catch (MyException e) {
      System.out.println(e.getMessage());
    }
  }
}

What will be the output?
AAge must be 18 or older
BException in thread "main" MyException
CNo output, program runs silently
DCompilation error due to missing default constructor
Step-by-Step Solution
Solution:
  1. Step 1: Analyze the validate method

    If age is less than 18, it throws MyException with a message.
  2. Step 2: Follow main method execution and catch block

    Calling validate(16) throws the exception, caught and prints the message via getMessage().
  3. Final Answer:

    Age must be 18 or older -> Option A
  4. Quick Check:

    Exception message printed from getMessage() [OK]
Quick Trick: Use getMessage() to print custom exception messages [OK]
Common Mistakes:
  • Expecting stack trace instead of message
  • Confusing default and parameterized constructors
  • Assuming no output if exception is caught

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Java Quizzes