Java OCA OCP Practice Question 650

Question

Given the following application, which type of exception will be printed in the stack trace at runtime?

package mypkg; /*w w  w.ja  va  2 s  .c o m*/
public class Main { 
   public static void main(String... hammer) { 
      try { 
         throw new ClassCastException(); 

      } catch (IllegalArgumentException e) { 
         throw new IllegalArgumentException(); 
      } catch (RuntimeException e) { 
         throw new NullPointerException(); 
      } finally { 
         throw new RuntimeException(); 
      } 
   } 
} 
  • A. IllegalArgumentException
  • B. NullPointerException
  • C. RuntimeException
  • D. The code does not compile.


C.

Note

For this question, notice that all the exceptions thrown or caught are unchecked exceptions.

First, the ClassCastException is thrown in the try block and caught by the second catch block since it inherits from RuntimeException, not IllegalArgumentException.

A NullPointerException is thrown, but before it can be returned the finally block is executed and a RuntimeException replaces it.

The application exits and the caller sees the RuntimeException in the stack trace, making Option C the correct answer.

If the finally block did not throw any exceptions, then Option B would be the correct answer.




PreviousNext

Related