OCA Java SE 8 Exception - OCA Mock Question Exception 9








Question

What is the output of the following program?

     1:  public class Main { 
     2:    public String name; 
     3:    public void parseName() { 
     4:      System.out.print("1"); 
     5:      try { 
     6:        System.out.print("2"); 
     7:        int x = Integer.parseInt(name); 
     8:        System.out.print("3"); 
     9:      } catch (NullPointerException e) { 
     10:       System.out.print("4"); 
     11:     } 
     12:     System.out.print("5"); 
     13:   } 
     14:   public static void main(String[] args) { 
     15:     Main m = new Main(); 
     16:     m.name = "Main"; 
     17:     m.parseName(); 
     18:     System.out.print("6"); 
     19:   } 
     20: } 
  1. 12, followed by a stack trace for a NumberFormatException
  2. 124, followed by a stack trace for a NumberFormatException
  3. 12456
  4. 12456
  5. 1256, followed by a stack trace for a NumberFormatException
  6. The code does not compile.
  7. An uncaught exception is thrown.




Answer



A.

Note

Line 4 prints 1.

The try block is entered, and line 6 prints 2.

Line 7 throws a NumberFormatException.

It isn't caught, so parseName ends.

main() doesn't catch the exception either, so the program terminates and the stack trace for the NumberFormatException is printed.

public class Main {
  public String name;
/*  w  ww  . j  a  v  a2  s  .c om*/
  public void parseName() {
    System.out.print("1");
    try {
      System.out.print("2");
      int x = Integer.parseInt(name);
      System.out.print("3");
    } catch (NullPointerException e) {
      System.out.print("4");
    }
    System.out.print("5");
  }

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

The code above generates the following result.