OCA Java SE 8 Exception - OCA Mock Question Exception 18








Question

What is printed before the NullPointerException from line 16?

     1: public class Main { 
     2:   public void go() { 
     3:     System.out.print("A"); 
     4:     try { 
     5:         stop(); 
     6:     } catch (ArithmeticException e) { 
     7:         System.out.print("B"); 
     8:     } finally { 
     9:         System.out.print("C"); 
     10:    } 
     11:    System.out.print("D"); 
     12:  } 
     13:  public void stop() { 
     14:    System.out.print("E"); 
     15:    String x = null; 
     16:    x.toString(); 
     17:    System.out.print("F"); 
     18:  } 
     19:  public static void main(String[] args) { 
     20:    new Main().go(); 
     21:  } 
     22: } 
  1. AE
  2. AEBCD
  3. AEC
  4. AECD
  5. No output appears other than the stack trace.




Answer



C.

Note

The main() method invokes go and A is printed.

The stop method is invoked and E is printed.

Line 16 throws a NullPointerException and line 17 doesn't execute.

The exception isn't caught in go since go only cares about ArithmeticException.

finally block executes and C is printed on line 9.

public class Main {
  public void go() {
    System.out.print("A");
    try {// w  w w . j  a  va 2 s .c  o  m
      stop();
    } catch (ArithmeticException e) {
      System.out.print("B");
    } finally {
      System.out.print("C");
    }
    System.out.print("D");
  }

  public void stop() {
    System.out.print("E");
    String x = null;
    x.toString();
    System.out.print("F");
  }
  public static void main(String[] args) {
    new Main().go();
  }
}