Java OCA OCP Practice Question 602

Question

What is the output of the following application?

package mypkg; //from w  ww  .  j  a va  2 s.  c  om
class Exception1 extends Exception {} 
class Transport { 
  public int travel() throws Exception1 { return 2; }; 
} 
public class Main { 
  public int travel() throws Exception { return 4; };  // j1 
  public static void main(String... distance) throws Exception{ 
     try { 
        System.out.print(new Main().travel()); 
     } catch (Exception e) ( 
        System.out.print(8); 
     ) 
  } 
} 
  • A. 4
  • B. 8
  • C. The code does not compile due to line j1.
  • D. The code does not compile for another reason.


D.

Note

The code does not compile because the catch block uses parentheses() instead of brackets {}, making Option D the correct answer.

Note that Main does not extend Transport, so while the override on line j1 appears to be invalid since Exception is a broader checked exception than Exception1, that code compiles without issue.

If the catch block was fixed, the code would output 4, making Option A the correct answer.




PreviousNext

Related