Java OCA OCP Practice Question 812

Question

What will be the output when the following code is compiled and run?

//in file Test.java 
class Exception1 extends Exception{  } 
class Exception2 extends Exception1  {  } 
class Test{ //from ww w  .ja  va 2s.  co m
   public static void main (String [] args){ 
      try{ 
         throw new Exception2 (); 
       } 
      catch (Exception1 e){ 
         System .out.println ("Exception1"); 
       } 
      catch (Exception e){ 
         System .out.println ("E"); 
       } 
      finally{ 
         System .out.println ("Finally"); 
       } 
    } 
} 

Select 1 option

  • A. It will not compile.
  • B. It will print Exception1 and Finally.
  • C. It will print Exception1, E and Finally.
  • D. It will print E and Finally.
  • E. It will print Finally.


Correct Option is  : B

Note

Since Exception2 is a sub class of Exception1, catch(Exception1 e) will be able to catch exceptions of class Exception2.

Therefore E 1 is printed.

Once the exception is caught the rest of the catch blocks at the same level are ignored.

So E is not printed. finally is always executed (except in case of System.exit()), so Finally is also printed.




PreviousNext

Related