Java Programming - Exceptions - Discussion

Discussion Forum : Exceptions - Pointing out the correct statements (Q.No. 1)
public class MyProgram 
    public static void main(String args[])
        FileOutputStream out = null;
            out = new FileOutputStream("test.txt");
        catch(IOException io) 
            System.out.println("IO Error.");
and given that all methods of class FileOutputStream, including close(), throw an IOException, which of these is true?
This program will compile successfully.
This program fails to compile due to an error at line 4.
This program fails to compile due to an error at line 6.
This program fails to compile due to an error at line 18.
Answer: Option

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.

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:

Your comments will be displayed after verification.