Java OCA OCP Practice Question 1775

Question

What is the result of compiling and executing the following class?

package mypkg;//from  w  w w.ja va  2 s  . com
public class Main {
   public static void main(String... rain) throws Exception {
      try (final AutoCloseable p = new AutoCloseable() {
         public void close() throws RuntimeException {}
      }) {
         System.out.println(p.toString());
      } catch (Exception e) {
         if(p != null) {
            p.close();
         }
      } finally {
         System.out.println("Main gone");
      }
   }
}
  • A. It prints one line.
  • B. It prints two lines.
  • C. It does not compile due to an error in the declaration of the p resource.
  • D. It does not compile for a different reason.


D.

Note

The code does not compile, making Options A and B incorrect.

The declaration of p uses an anonymous inner class that correctly overrides the close() method.

The overridden methods cannot throw any new or broader checked exceptions than the inherited method.

Alternatively, they can avoid throwing inherited checked exceptions or declare new unchecked exceptions, such as RuntimeException.

The compilation error is in the catch block of the main() method, where the p variable is out of scope.

In try-with-resources statements, the resources are only accessible in the try block.

Option D is the correct answer.




PreviousNext

Related