Java Programming - Exceptions - Discussion

Discussion :: 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?

[A]. This program will compile successfully.
[B]. This program fails to compile due to an error at line 4.
[C]. This program fails to compile due to an error at line 6.
[D]. This program fails to compile due to an error at line 18.

Answer: Option D

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.


Kullayappa said: (Feb 1, 2012)  
I think closing of file can also be done in finally block also.

Magnus said: (Apr 4, 2012)  
out.close() can be written in finally block

Puneeth said: (May 21, 2012)  
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.

Harshita said: (Mar 3, 2018)  
I am not able to understand this one. So please help me.

Raj said: (Oct 17, 2018)  
Anyone can explain in detail?

Post your comments here:

Name *:

Email   : (optional)

» Your comments will be displayed only after manual approval.