ProgrammingHardTCS NQT · Infosys pattern

What is printed?

What is printed?
class MyChecked extends Exception {
    MyChecked(String m) { super(m); }
}
public class Main {
    static void risky() throws MyChecked {
        throw new MyChecked("fail");
    }
    public static void main(String[] args) {
        try {
            risky();
        } catch (Exception e) {
            System.out.println("Caught: " + e.getMessage());
        }
    }
}
  1. A. Caught: fail
  2. B. Compilation error: Exception cannot catch MyChecked
  3. C. It crashes with an uncaught MyChecked
  4. D. Compilation error: main must declare throws MyChecked

Correct answer: A. Caught: fail

MyChecked is a checked exception (extends Exception), and risky() correctly declares `throws MyChecked`. A catch(Exception e) clause catches any Exception subtype, including MyChecked, so it's caught and its message printed: "Caught: fail".

More OOP with C++ and Java questions

Exams that ask this topic