ProgrammingHardWipro · Cognizant pattern

Does this compile?

Does this compile?
class MyException extends Exception {}
class Demo {
    void risky() throws MyException { throw new MyException(); }
    void call() {
        risky();
    }
}
  1. A. Yes, checked exceptions only need to be declared, not caught
  2. B. No: MyException is a checked exception, so call() must either catch it or declare throws MyException
  3. C. Yes, because MyException extends Exception rather than RuntimeException
  4. D. No: risky() cannot throw a custom exception type

Correct answer: B. No: MyException is a checked exception, so call() must either catch it or declare throws MyException

MyException extends Exception (not RuntimeException), making it a checked exception. Any method whose body can let a checked exception propagate must either catch it or declare it in its own throws clause; call() does neither, so it fails to compile.

More OOP with C++ and Java questions

Exams that ask this topic