Java OCA OCP Practice Question 267

Question

Given:

class Main {/*from w ww. jav  a  2s  .  c o m*/
  static String s = "-";
  class MyClass implements AutoCloseable {
    public void t()     {    s += "t";   }
    public void close() {    s += "c";   }
  }
  public static void main(String[] args) {
    new Main().run();
    System.out.println(s);
  }

  public void run() {
      try (MyClass w = new MyClass()) {
         w.t();
         s += "1";
         throw new Exception();
      } catch (Exception e) { 
         s += "2";
      } finally { 
         s += "3"; 
      } 
  } 
}

What is the result?

  • A. -t123t
  • B. -t12c3
  • C. -t123
  • D. -t1c3
  • E. -t1c23
  • F. None of the above; main() throws an exception
  • G. Compilation fails


E is correct.

Note

After the exception is thrown, Automatic Resource Management calls close() before completing the try block.

From that point, catch and finally execute in the normal order.

F is incorrect because the catch block catches the exception and does not rethrow it.




PreviousNext

Related