Bird
0
0

What will be the output of the following code?

medium📝 Predict Output Q13 of 15
Java - Custom Exceptions
What will be the output of the following code?
public class Test {
  static void method() throws Exception {
    throw new Exception("Error occurred");
  }
  public static void main(String[] args) {
    try {
      method();
    } catch (Exception e) {
      System.out.println(e.getMessage());
    }
  }
}
ACompilation error
BException in thread "main" java.lang.Exception
CNo output
DError occurred
Step-by-Step Solution
Solution:
  1. Step 1: Analyze method throwing exception

    The method explicitly throws a new Exception with message "Error occurred".
  2. Step 2: Check exception handling in main

    The main method calls method() inside try-catch. The catch block prints the exception message.
  3. Final Answer:

    Error occurred -> Option D
  4. Quick Check:

    Exception caught and message printed = C [OK]
Quick Trick: Exception message prints if caught in try-catch [OK]
Common Mistakes:
  • Assuming uncaught exception causes crash
  • Confusing exception message with full stack trace
  • Thinking code won't compile without throws in main

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Java Quizzes