Bird
0
0

What will be the output of this code?

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

public class Test {
  public static void main(String[] args) {
    try {
      throw new MyException();
    } catch (MyException e) {
      System.out.println("Caught MyException");
    } catch (Exception e) {
      System.out.println("Caught Exception");
    }
  }
}
ACaught Exception
BNo output
CCaught MyException
DCompilation error
Step-by-Step Solution
Solution:
  1. Step 1: Analyze the thrown exception type

    The code throws MyException, a subclass of Exception.
  2. Step 2: Check catch block order

    The first catch matches MyException exactly, so it executes and prints the message.
  3. Final Answer:

    Caught MyException -> Option C
  4. Quick Check:

    Specific catch runs before general one [OK]
Quick Trick: Catch specific exceptions before general ones [OK]
Common Mistakes:
  • Expecting the general Exception catch to run first
  • Thinking code won't compile due to catch order
  • Assuming no output because exception is thrown

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Java Quizzes