Java OCA OCP Practice Question 2158

Question

What is the output of the following application?.

package mypkg; /*w  w  w . j  a  v a 2s . com*/


class AddingException extends Exception {}; 
class DividingException extends Exception {}; 
class UnexpectedException extends RuntimeException {}; 


public class Main { 
   
   public void m() throws Throwable { 
      try { 
         throw new IllegalStateException(); 
      } catch (AddingException | DividingException e) {  // p1 
         System.out.println("Math Problem"); 
      } catch (UnexpectedException | Exception f) {  // p2 
         System.out.println("Unknown Error"); 
         throw f; 
      } 
   } 
   public static void main(String[] numbers) throws Throwable { 
      try { 
         new Main().m(); 
      } finally { 
         System.out.println("All done!"); 
      } 
   } 
} 
  • A. Math Problem
  • B. Unknown Problem
  • C. Unknown Problem followed by All done!
  • D. The code does not compile solely due to line p1.
  • E. The code does not compile solely due to line p2.
  • F. The code does not compile due to lines p1 and p2.


F.

Note

The first catch block on line p1 does not compile because AddingException and DividingException are checked exceptions, and the compiler detects these exceptions are not capable of being thrown by the associated try block.

The second catch block on line p2 also does not compile, although for a different reason.

UnexpectedException is a subclass of RuntimeException, which in turn extends Exception.

This makes UnexpectedException a subclass of Exception, causing the compiler to consider UnexpectedException redundant.

For these two reasons, the code does not compile, and Option F is the correct answer.




PreviousNext

Related