Java OCA OCP Practice Question 1157

Question

What will be printed when the following program is compiled and run?

public class Main{ 
   public static void main (String args []) throws Exception{ 
       try{ /*from  w w  w  . ja  v a 2 s  .  co m*/
          method1 (); 
          System.out.println ("A"); 
       } 
       finally{ 
          System.out.println ("B"); 
       } 
       System.out.println ("C"); 
   } 
   public static void method1 () throws Exception  { throw new Exception ();  } 
} 

Select 1 option

  • A. It will print C and B, in that order.
  • B. It will print A and B, in that order.
  • C. It will print B and throw Exception.
  • D. It will print A, B and C in that order.
  • E. Compile time error.


Correct Option is  : C

Note

An Exception is thrown in method method1 () so println ("A") will not be executed.

As there is no catch block the exception will not be handled and the main () method will propagate the exception.

So println ("C"); will also not be executed.

'finally' block is always executed (even if there is a return in try but not if there is System.exit() ) so println ("B") is executed.




PreviousNext

Related