Java OCA OCP Practice Question 1420

Question

How many lines of the following application do not compile?

package mypkg; /*from www  .j  a v a  2 s.co m*/
class Exception1 extends Exception {} 
class Exception2 extends Exception1 {} 

public class Palace { 
   public void m() throws Exception { 
      try { 
         throw new Exception("Problem"); 
      } catch (Exception1 e) { 
         throw new Exception1(); 
      } catch (Exception2 ex) { 
         try { 
            throw new Exception1(); 
         } catch (Exception ex) { 
         } finally { 
            System.out.println("Almost done"); 
         } 
      } finally { 
         throw new RuntimeException("Unending problem"); 
      } 
   } 
   public static void main(String[] moat) throws IllegalArgumentException { 
      new Palace().m(); 
   } 
} 
  • A. None. The code compiles and produces a stack trace at runtime.
  • B. One
  • C. Two
  • D. Three
  • E. Four
  • F. Five


D.

Note

The first compilation problem with the code is that the second catch block in m() is unreachable since Exception2 is a subclass of Exception1.

The catch blocks should be ordered with the more narrow exception classes before the broader ones.

Next, the variable ex is declared twice within the same scope since it appears in the second catch block as well as the embedded try-catch block.

The m() method declares the checked Exception class, but it is not handled in the main() method with a try-catch block, nor in the main() method declaration.

Option D is correct.




PreviousNext

Related