Monday, July 7, 2014

OCJP practice question #25

3:17 PM

What will be the output  of following java program? Assume that File1.txt exists.


import java.io.*;
class TestIO
{
        public static void main(String[] args)
        {
                try
                {
                        FileReader fis=new FileReader("File1.txt");
                        FileWriter fos=new FileWriter("File1Output.txt");
                        int data;
                        while((data=fis.read())!=-1)
                        {
                                fos.write(data);
                        }
                        fos.flush();
                }
                catch (Exception e)
                {
                        System.out.println(e);
                }
                catch (IOException ioe)
                {
                        System.out.println(ioe);
                }
               
        }
}


 Options:
      
  1. Output file will have same content as in input File1.txt.
  2. An exception will be raised during run time.
  3. Compilation fails.
  4. Nothing will be printed in output file.


Answer:

Option C is correct, a compile time error will be thrown by the compiler because of the catch block ordering.


Explanation:

Since Exception is a super class of all exceptions, any exception raised during the flow of program will go to first catch block always, never in second block.

You can write multiple catch blocks in java but child exceptions must come first than parent exceptions. (Vice versa makes the compilation process fail.)


Also, note that sibling exceptions order in catch block does not matter. 

0 comments :

Post a Comment

 

© 2014 DieHardTechy . All rights resevered. Designed by Diehardtechy