OCA Java SE 8 Mock Exam - OCA Mock Question 22








Question

What is the output of the following code?

public class Main {
  void method() {
    try {
      myMethod();
      return;
    } finally {
      System.out.println("finally 1");
    }
  }

  void myMethod() {
    System.out.println("myMethod");
    throw new StackOverflowError();
  }

  public static void main(String args[]) {
    Main var = new Main();
    var.method();
  }
}

             a  myMethod 
                finally 1 

             b  myMethod 
                finally 1 
                Exception in thread "main" java.lang.StackOverflowError 

             c  myMethod 
                Exception in thread "main" java.lang.StackOverflowError 

             d  myMethod 

             e  The code fails to compile. 




Answer



B

Note

The method myMethod throws StackOverflowError, which is not a checked exception.

The call to the method myMethod is immediately followed by the keyword return, which is supposed to end the execution of the method method. But the call to myMethod is placed within a try-catch block, with a finally block.

Because myMethod doesn't handle the error StackOverflowError itself, the control looks for the exception handler in the method method.

This calling method doesn't handle this error, but defines a finally block.

The control then executes the finally block.

public class Main {
  void method() {
    try {/*from  ww  w.  ja  va2s .c o  m*/
      myMethod();
      return;
    } finally {
      System.out.println("finally 1");
    }
  }

  void myMethod() {
    System.out.println("myMethod");
    throw new StackOverflowError();
  }

  public static void main(String args[]) {
    Main var = new Main();
    var.method();
  }
}