Java OCA OCP Practice Question 2438

Question

Tom defines two custom exception classes:

class Exception1 extends IOException {}
class Exception2 extends FileNotFoundException {}

When Paul tries to use these exception classes in his own interfaces, the code doesn't compile:.

interface Base {
    void read() throws Exception1;
}
interface Derived extends Base {
    void read() throws Exception2;
}

Which definition of read() in the Derived interface compiles successfully?

  • a void read() throws FileNotFoundException;
  • b void read() throws IOException;
  • c void read();
  • d void read() throws Exception;
  • e void read() throws Exception1;
  • f void read() throws RuntimeException;
  • g void read() throws Throwable;


c, e, f

Note

Though the question seems to be testing you on the hierarchy of exception classes IOException and FileNotFoundException, it's not.

This question is about creating custom exception classes with overridden methods that throw exceptions.

To understand the explanation, note the following class hierarchies:.

  • Exception FileNotFoundException extends IOException.
  • Exception Exception1 extends IOException.
  • Exception Exception2 extends FileNotFoundException.
  • Exception Exception2 doesn't extend Exception1.

This class hierarchy implies the following:.

  • Exception1 isn't a type of Exception2.
  • Exception1 and FileNotFoundException are unrelated exceptions.

To override read() in the Base interface, read() in the Derived interface must either declare to throw a Exception1, any derived classes of Exception1, any runtime exception or errors, or no exception.

Option (a) is incorrect because FileNotFoundException is unrelated to BaseException.

Options (b), (d), and (g) are incorrect because IOException, Exception, and Throwable are all super classes of Exception1 (and not sub classes) and therefore invalid when overriding method read().




PreviousNext

Related