ProgrammingHardWipro · Cognizant pattern

What is printed?

What is printed?
class MyChecked extends Exception {}
class Test {
    static void risky() throws MyChecked { throw new MyChecked(); }
    public static void main(String[] args) {
        try {
            risky();
        } catch (Exception e) {
            System.out.println("caught: " + e.getClass().getSimpleName());
        }
    }
}
  1. A. Compilation error: MyChecked must be caught specifically, not as Exception
  2. B. caught: Exception
  3. C. Uncaught exception at runtime
  4. D. caught: MyChecked

Correct answer: D. caught: MyChecked

A catch(Exception e) clause catches any exception of type Exception or any subclass, including the custom checked MyChecked. getClass().getSimpleName() reports the actual runtime class, MyChecked, not the static catch type.

More OOP with C++ and Java questions

Exams that ask this topic