Home / Java Programming / Exceptions :: Discussion

Discussion :: Exceptions

  1. and given that all methods of class FileOutputStream, including close(), throw an IOException, which of these is true?
    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();
            }
        }
    }
    
  2. 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.

    View Answer

    Workspace

    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.


Be The First To Comment