Join
Blogs
Questions
Videos
Tags
Members
Search
 
 
Create your own blog, earn points and get popular!

What will be the output of following program?

  1. public class Q3{
  2.  
  3.  public static void main(String args[]){
  4.   try{
  5.    Demo d = new Demo();
  6.    d.method1();
  7.    System.out.println("Main Completed");
  8.   }catch(Exception e){}
  9.  }
  10. }
  11.  
  12. class Demo{
  13.  
  14.  public void method2(){
  15.   throw new ArrayIndexOutOfBoundsException();
  16.  }
  17.  
  18.  public void method1(){
  19.   try{
  20.    method2();
  21.   }catch(NullPointerException ae){
  22.    System.out.println("Exception caught");
  23.   }finally{
  24.    System.out.println("Method 1 ends");
  25.   }
  26.  }
  27. }
a. Program will not compile
b.Program will print "Method 1 ends"
c. Program will print "Exception Caught"
d. Program will print Main Completed

  Answer:

Correct choice is B - program will print Method 1 ends. Method 1 calls the method 2 which throws ArrayIndexOutOfBoundsException, but that is not caught anywhere in the method 1. So, this excpetion will be thrown again to the calling main method and will be caught in main method's catch block. However, before program exits, it goes in the finally block of method 1 and prints "Method 1 ends". Remember, finally block is ALWAYS executed in normal scenario in the event of exception or not.
No votes yet
Share this

Post new comment

4 + 1 =
Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.