Java OCA OCP Practice Question 617

Question

What is the output of the following application?

package mypkg; /*w w w  . j a va2 s . co  m*/
public class Main { 
   public void m() throws Exception { 
      throw new RuntimeException("Error processing request"); 
   } 
   public static void main(String[] bits) { 
      try { 
         new Main().m(); 
         System.out.print("Ping"); 
      } catch (NullPointerException e) { 
         System.out.print("Pong"); 
         throw e; 
      } 
   } 
} 
  • A. Ping
  • B. Pong
  • C. The code does not compile.
  • D. The code compiles but throws an exception at runtime.


C.

Note

The code does not compile due to the call to m() in the main() method.

Even though the m() method only throws an unchecked exception, its method declaration includes the Exception class, which is a checked exception.

The checked exception must be handled or declared in the main() method in which it is called.

While there is a try-catch block in the main() method, it is only for the unchecked NullPointerException.

Since Exception is not a subclass of NullPointerException, the checked Exception is not properly handled or declared and the code does not compile, making Option C the correct answer.




PreviousNext

Related