Java OCA OCP Practice Question 1808

Question

What is the minimal list of exception classes that the overriding method f() in the following code must declare in its throws clause before the code will compile correctly?.

 class MyBaseClass {
   // InterruptedException is a direct subclass of Exception.
   void f() throws ArithmeticException, InterruptedException {
    div(5, 5);/*from w ww .  j av  a 2 s  . c om*/
  }

  int div(int i, int j) throws ArithmeticException {
    return i/j;
  }
}

public class Main extends MyBaseClass {
  void f() /* throws [...list of exceptions...] */ {
    try {
      div(5, 0);
    } catch (ArithmeticException e) {
      return;
    }
    throw new RuntimeException("ArithmeticException was expected.");
  }
}

Select the one correct answer.

  • (a) Does not need to specify any exceptions.
  • (b) Needs to specify that it throws ArithmeticException.
  • (c) Needs to specify that it throws InterruptedException.
  • (d) Needs to specify that it throws RuntimeException.
  • (e) Needs to specify that it throws both ArithmeticException and InterruptedException.


(a)

Note

Overriding methods can specify all, none, or a subset of the checked exceptions the overridden method declares in its throws clause.

The InterruptedException is the only checked exception specified in the throws clause of the overridden method.

The overriding method f() need not specify the InterruptedException from the throws clause of the overridden method, because the exception is not thrown here.




PreviousNext

Related