Bird
0
0

What will be the output of this code?

medium📝 Predict Output Q13 of 15
Java - Custom Exceptions
What will be the output of this code?
class MyException extends Exception {}

public class Test {
  public static void check(int num) throws MyException {
    if (num < 0) throw new MyException();
    else System.out.println("Number is " + num);
  }

  public static void main(String[] args) {
    try {
      check(-5);
    } catch (MyException e) {
      System.out.println("Caught MyException");
    }
  }
}
ACaught MyException
BNumber is -5
CCompilation error
DNo output
Step-by-Step Solution
Solution:
  1. Step 1: Understand the check method behavior

    If the number is less than 0, it throws MyException. Since -5 < 0, exception is thrown.
  2. Step 2: Analyze main method's try-catch

    The exception is caught in the catch block, which prints "Caught MyException".
  3. Final Answer:

    Caught MyException -> Option A
  4. Quick Check:

    Exception thrown and caught = "Caught MyException" [OK]
Quick Trick: Exception thrown for negative, caught prints message [OK]
Common Mistakes:
  • Expecting negative number print instead of exception
  • Thinking code won't compile due to throws
  • Missing catch block effect

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Java Quizzes