Java OCA OCP Practice Question 1810

Question

What, if anything, would cause the following code not to compile?.

class MyBaseClass {
  void f() throws ArithmeticException {
    //...//from  ww  w  .j  av a  2s . co m
  }
}

public class Main extends MyBaseClass {
  public static void main(String[] args) {
    MyBaseClass obj = new Main();

    try {
      obj.f();
    } catch (ArithmeticException e) {
      return;
    } catch (Exception e) {
      System.out.println(e);
      throw new RuntimeException("Something wrong here");
    }
  }

  // InterruptedException is a direct subclass of Exception.
  void f() throws InterruptedException {
    //...
  }
}

Select the one correct answer.

  • (a) The main() method must declare that it throws RuntimeException.
  • (b) The overriding f() method in Main must declare that it throws ArithmeticException, since the f() method in class MyBaseClass declares that it does.
  • (c) The overriding f() method in Main is not allowed to throw InterruptedException, since the f() method in class MyBaseClass does not throw this exception.
  • (d) The compiler will complain that the catch(ArithmeticException) block shadows the catch(Exception) block.
  • (e) You cannot throw exceptions from a catch block.
  • (f) Nothing is wrong with the code, it will compile without errors.


(c)

Note

The overriding f() method in Main is not permitted to throw the checked InterruptedException, since the f() method in class MyBaseClass does not throw this exception.

To avoid compilation errors, either the overriding f() method must not throw an InterruptedException or the overridden f() method must declare that it can throw an InterruptedException.




PreviousNext

Related