Java OCA OCP Practice Question 1781

Question

Which statement about the following program is correct?

package mypkg;/*ww w .j  a va 2  s . c om*/
public class Main {
   public int play(String n) throws Exception {
      try {
         throw new RuntimeException(n);
      } catch (Exception e) {
         throw new RuntimeException(e);
      }
   }
   public static final void main(String[] ball) throws RuntimeException {
      new Main().play("ball");
      new Main().play("water");
   }
}
  • A. The program prints one exception at runtime.
  • B. The program prints two exceptions at runtime.
  • C. The class does not compile because of the play() method.
  • D. The class does not compile because of the main() method.


D.

Note

The play() method compiles without issue, re-throwing a wrapped exception in the catch block.

While the main() method does declare RuntimeException, it does not declare or catch the Exception thrown by the calls to play().

Even though the play() method does not appear to actually throw an instance of Exception, because it is declared, the main() method must catch or declare it.

Since the checked exception is not handled, the main() method does not compile, and Option D is the correct answer.

If the main() method was changed to declare the appropriate checked exception, then the rest of the code would compile, and exactly one exception would be printed, making Option A the correct answer.




PreviousNext

Related