Java OCA OCP Practice Question 275

Question

Given:

public class Main {
   class MyClass implements AutoCloseable {
      public void close() {
         throw new RuntimeException("a");
      }//from www  .j av  a  2 s .  co  m
   }

   public static void main(String[] args) throws IOException {
      new Main().run();
   }

   public void run() throws IOException {
      try (MyClass l = new MyClass();) {
         throw new IOException();
      } catch (Exception e) {
         throw e;

      }
   }
}

Which exceptions will the code throw?

  • A. IOException with suppressed RuntimeException a
  • B. IOException with suppressed RuntimeException c
  • C. RuntimeException a with no suppressed exception
  • D. RuntimeException c with no suppressed exception
  • E. RuntimeException a with suppressed RuntimeException c
  • F. RuntimeException c with suppressed RuntimeException a
  • G. Compilation fails


A is correct.

Note

After the try block throws an IOException, Automatic Resource Management calls close() to clean up the resources.

Since an exception was already thrown in the try block, RuntimeException a gets added to it as a suppressed exception.

The catch block merely re-throws the caught exception.

The code does compile even though the catch block catches an Exception and the method merely throws an IOException.

In Java 7, the compiler is able to pick up on this.




PreviousNext

Related