Bird
0
0

What will be the output of this code snippet?

medium📝 Predict Output Q5 of 15
Java - Custom Exceptions
What will be the output of this code snippet?
class MyException extends Exception {}
public class Demo {
  static void test(int val) throws MyException {
    if (val == 0) throw new MyException();
    System.out.println("Value: " + val);
  }
  public static void main(String[] args) {
    try {
      test(10);
      test(0);
    } catch (MyException e) {
      System.out.println("Exception caught");
    }
  }
}
AValue: 10 Value: 0
BException caught Value: 0
CValue: 10 Exception caught
DCompilation error due to missing catch block
Step-by-Step Solution
Solution:
  1. Step 1: Trace the first call to test(10)

    Since 10 != 0, it prints "Value: 10" and continues.
  2. Step 2: Trace the second call to test(0)

    Since val == 0, it throws MyException, which is caught in the catch block printing "Exception caught".
  3. Final Answer:

    Value: 10 Exception caught -> Option C
  4. Quick Check:

    First prints value, second throws and catches exception [OK]
Quick Trick: Exception stops normal flow and jumps to catch block [OK]
Common Mistakes:
  • Expecting both values to print
  • Thinking exception is thrown but not caught
  • Confusing order of output lines

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Java Quizzes