Pages

Wednesday 11 September 2013

Exception - tricky interview questions

1) find the o/p of the following


package com.kb.client;

public class Exception1 {

 
 public static void main(String[] args) {
  String value = getValue();
  System.out.println(value);

 }

 private static String getValue() {
  
  try {
   System.out.println("before return from try");
   return "from try";
   
  } catch (Exception e) {
   System.out.println("before return from catch");
   return "from catch";
  }
  finally{
   System.out.println("before return from finally");
   return "from finally";
  }
 }

}
 
here when the control enters the try block it first prints the first line 
before return from trythen it has return statement , but finally should execute before try completes so control goes to finally, it prints finally block's first statement
 and it finds the return statement there so it returns from finally.
so output would be
 
before return from try
before return from finally
from finally
 
 
now i will put exception statement in try block as below
 
package com.kb.client;

public class Exception1 {

 
 public static void main(String[] args) {
  String value = getValue();
  System.out.println(value);

 }

 private static String getValue() {
  
  try {
   int i = 10/0;
   System.out.println("before return from try");
   return "from try";
   
  } catch (Exception e) {
   System.out.println("before return from catch");
   return "from catch";
  }
  finally{
   System.out.println("before return from finally");
   return "from finally";
  }
 }

}
 
in this case find the o/p ?

as explained above but try gets with the exception so catch starts execution and executes finally before catch returns so 
the o/p will be as below 

before return from catch
before return from finally
from finally

now if we comment return from finally for the above program as below

package com.kb.client;

public class Exception1 {

 
 public static void main(String[] args) {
  String value = getValue();
  System.out.println(value);

 }

 private static String getValue() {
  
  try {
   int i = 10/0;
   System.out.println("before return from try");
   return "from try";
   
  } catch (Exception e) {
   System.out.println("before return from catch");
   return "from catch";
  }
  finally{
   System.out.println("before return from finally");
   //return "from finally";
  }
 }

}
 
now in this case try as soon as get exception control goes to catch and catch executes first line and before executing return it goes to finally and executes first line .
since return in finally is commented it goes back to catch and executes return from catch.
so o/p would be as below

before return from catch
before return from finally
from catch