Java OCA OCP Practice Question 1801

Question

How many lines of text does the following program print?

package mypkg;/*from ww  w.  j  a v  a 2  s . co m*/
class Login implements AutoCloseable {
   public void close() throws Exception {}
}
public class LightCycle {
   public static void main(String... bits) {
      try (Login l = new Login()) {
         System.out.println("ping");
      } finally {
         System.out.println("pong");
      }
      System.out.println("return");
   }
}
  • A. One
  • B. Two
  • C. Three
  • D. The code does not compile.


D.

Note

The code does not compile because the close() method throws an Exception that is not handled or declared in the main() method, making Option D the correct answer.

When a try-with-resources statement is used with a close() method that throws a checked exception, it must be handled by the method or caught within the try-with-resources statement.




PreviousNext

Related