OCA Java SE 8 Exception - OCA Mock Question Exception 5








Question

What is printed by the following? (Choose all that apply)

     1:  public class Main { 
     2:    public String name; 
     3:    public void run() { 
     4:      System.out.print("1"); 
     5:      try { 
     6:        System.out.print("2"); 
     7:        name.toString(); 
     8:        System.out.print("3"); 
     9:      } catch (NullPointerException e) { 
     10:       System.out.print("4"); 
     11:       throw e; 
     12:     } 
     13:     System.out.print("5"); 
     14:   } 
     15:   public static void main(String[] args) { 
     16:     Main m = new Main(); 
     17:     m.run(); 
     18:     System.out.print("6"); 
     19:   } } 
  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. The stack trace for a NullPointerException




Answer



A, B, D, G.

Note

Line 4 prints 1 and line 6 prints 2, so options A and B are correct.

Line 7 throws a NullPointerException, which causes line 8 to be skipped, so C is incorrect.

The exception is caught on line 9 and line 10 prints 4.

Line 11 throws the exception again, which causes run() to immediately end, so line 13 doesn't execute and E is incorrect.

The main() method doesn't catch the exception either, so line 18 doesn't execute and F is incorrect.

The uncaught NullPointerException prints out the stack trace, so G is correct.

public class Main {
  public String name;
/* w  w  w  .jav  a2 s .  c o  m*/
  public void run() {
    System.out.print("1");
    try {
      System.out.print("2");
      name.toString();
      System.out.print("3");
    } catch (NullPointerException e) {
      System.out.print("4");
      throw e;
    }
    System.out.print("5");
  }

  public static void main(String[] args) {
    Main m = new Main();
    m.run();
    System.out.print("6");
  }
}