Java OCA OCP Practice Question 1802

Question

Which digits, and in what order, will be printed when the following program is compiled and run?.

public class Main {
  public static void main(String[] args) {
    try {//  ww w . jav  a 2 s .co m
      f();
    } catch (InterruptedException e) {
      System.out.println("1");
      throw new RuntimeException();
    } catch (RuntimeException e) {
      System.out.println("2");
      return;
    } catch (Exception e) {
      System.out.println("3");
    } finally {
      System.out.println("4");
    }
    System.out.println("5");
  }

  // InterruptedException is a direct subclass of Exception.
  static void f() throws InterruptedException {
    throw new InterruptedException("Time for lunch.");
  }
}

Select the one correct answer.

  • (a) The program will print 5.
  • (b) The program will print 1 and 4, in that order.
  • (c) The program will print 1, 2, and 4, in that order.
  • (d) The program will print 1, 4, and 5, in that order.
  • (e) The program will print 1, 2, 4, and 5, in that order.
  • (f) The program will print 3 and 5, in that order.


(b)

Note

The program will print 1 and 4, in that order.

An InterruptedException is handled in the first catch block.

Inside this block a new RuntimeException is thrown.

This exception was not thrown inside the try block and will not be handled by the catch blocks, but will be sent to the caller of the main() method.

Before this happens, the finally block is executed.

The code to print 5 is never reached, since the RuntimeException remains uncaught after the execution of the finally block.




PreviousNext

Related