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:
- Output file will have same content as in input File1.txt.
- An exception will be raised during run time.
- Compilation fails.
- 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.
No comments:
Post a Comment