ProgrammingHardProduct-company MCQ pattern

Does this compile?

Does this compile?
class A { void m() throws java.io.IOException {} }
class B extends A {
    @Override
    void m() throws java.io.FileNotFoundException {}
}
  1. A. No: an overriding method must declare the exact same throws clause as the superclass method
  2. B. Yes: FileNotFoundException is a subtype of IOException, so narrowing the throws clause is allowed
  3. C. No: overriding methods cannot declare any checked exception
  4. D. Yes, but only if B.m() is also declared final

Correct answer: B. Yes: FileNotFoundException is a subtype of IOException, so narrowing the throws clause is allowed

An overriding method may declare a checked exception that is the same as, or a subtype of, the one declared in the overridden method (or declare none at all). FileNotFoundException extends IOException, so this narrowing is legal.

More OOP with C++ and Java questions

Exams that ask this topic