Bird
0
0

What will be the output of the following Java code?

medium📝 Predict Output Q13 of 15
Java - Custom Exceptions
What will be the output of the following Java code?
class MyException extends Exception {
    public MyException(String message) {
        super(message);
    }
}

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

    public static void main(String[] args) {
        try {
            check(-5);
        } catch (MyException e) {
            System.out.println(e.getMessage());
        }
    }
}
ANegative number not allowed
BCompilation error
CNumber is -5
DNo output
Step-by-Step Solution
Solution:
  1. Step 1: Analyze the check method behavior

    If the input number is less than 0, it throws a MyException with message "Negative number not allowed"; otherwise, it prints the number.
  2. Step 2: Follow the main method execution

    Main calls check(-5), which triggers the exception because -5 < 0. The exception is caught and its message is printed.
  3. Final Answer:

    Negative number not allowed -> Option A
  4. Quick Check:

    Exception message printed = C [OK]
Quick Trick: Exception message prints when thrown and caught [OK]
Common Mistakes:
  • Expecting the number to print despite exception
  • Thinking code causes compilation error
  • Ignoring exception catch block

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Java Quizzes