Java Programming - Exceptions - Discussion
Discussion Forum : Exceptions - Pointing out the correct statements (Q.No. 1)
1.
import java.io.*;
public class MyProgram
{
public static void main(String args[])
{
FileOutputStream out = null;
try
{
out = new FileOutputStream("test.txt");
out.write(122);
}
catch(IOException io)
{
System.out.println("IO Error.");
}
finally
{
out.close();
}
}
}
and given that all methods of class FileOutputStream, including close(), throw an IOException, which of these is true?Answer: Option
Explanation:
Any method (in this case, the main() method) that throws a checked exception (in this case, out.close() ) must be called within a try clause, or the method must declare that it throws the exception. Either main() must declare that it throws an exception, or the call to out.close() in the finally block must fall inside a (in this case nested) try-catch block.
Discussion:
6 comments Page 1 of 1.
Anni said:
1 year ago
Explain it please.
Raj said:
4 years ago
Anyone can explain in detail?
Harshita said:
5 years ago
I am not able to understand this one. So please help me.
Puneeth said:
1 decade ago
You both are right. While close() on FileOutputStream class object can also throw IOException we need to either catch it in try catch block inside finally or indicate the method itself throws IOException.
Magnus said:
1 decade ago
out.close() can be written in finally block
Kullayappa said:
1 decade ago
I think closing of file can also be done in finally block also.
Post your comments here:
Quick links
Quantitative Aptitude
Verbal (English)
Reasoning
Programming
Interview
Placement Papers