OCA Java SE 8 Exception - OCA Mock Question Exception 8








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 (NumberFormatException e) { 
     10:       System.out.print("4"); 
     11:     } 
     12:   } 
     13:   public static void main(String[] args) { 
     14:     Main r = new Main(); 
     15:     r.name = "Main"; 
     16:     r.parseName(); 
     17:     System.out.print("5"); 
     18:   } 
     19: } 
  1. 12
  2. 1234
  3. 1235
  4. 124
  5. 1245
  6. The code does not compile.
  7. An uncaught exception is thrown.




Answer



E.

Note

Line 4 prints 1.

The try block executes and 2 is printed.

Line 7 throws a NumberFormatException, so line 8 doesn't execute.

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

Because the exception is handled, execution resumes normally.

parseName finishes without issues, and line 17 executes, printing 5.

That's the end of the program, so the output is 1245.

public class Main {
  public String name;
//from w w w .jav  a  2s .  co m
  public void parseName() {
    System.out.print("1");
    try {
      System.out.print("2");
      int x = Integer.parseInt(name);
      System.out.print("3");
    } catch (NumberFormatException e) {
      System.out.print("4");
    }
  }

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

The code above generates the following result.