Java OCA OCP Practice Question 2448

Question

What's the output of the following code?

class Box implements AutoCloseable {
   public void close() throws Exception {
      System.out.println("close");
      throw new Exception();
   }//from  w w  w  .  j a  v a  2 s  . c  o m
}

class Main {
   public static void main(String args[]) {
      try (Box box = new Box()) {
         box.close();
         box.close();
      } catch (Exception e) {
         System.out.println("catch:" + e);
      } finally {
         System.out.println("finally");
      }
   }
}
a  catch:java.lang.Exception

b  close//w  ww.j a v a 2s . c om
   catch:java.lang.Exception
   finally

c  close
   close
   catch:java.lang.Exception
   finally

d  close
   close
   catch:java.lang.Exception
   catch:java.lang.Exception
   finally

e  close
   close
   java.lang.CloseException
   finally

f  close
   java.lang.RuntimeException
   finally


c

Note

This question tries to trick you with explicit calls of method close() placed in the try block.

Though close() is implicitly called to close a resource, it's possible to call it explicitly in the try block.

But the explicit call to close() is independent of the implicit call to close() for each resource defined in the try-with- resources statement.

The first call to method close() prints close.

Because this method call throws an exception, the control is ready to be transferred to the catch block and thus the second explicit call to method close() doesn't execute.

But before the control is moved to the catch block, the implicit call to method close() is made, which again prints close and throws an exception.

The exception thrown by the implicit call of method close() is suppressed by the exception thrown by the explicit call of method close(), placed before the end of the try block.

The control is then transferred to the catch block and, last, to the finally block.




PreviousNext

Related