Java I/O (checked exceptions) — will this program compile given that FileOutputStream.close() throws IOException? 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(); } } } Choose the best answer.
-
AThis program will compile successfully.
-
BThis program fails to compile due to an error at line 4.
-
CThis program fails to compile due to an error at line 6.
-
DThis program fails to compile due to an error at line 18.
Answer
Correct Answer: This program fails to compile due to an error at line 18.
Explanation
Introduction / Context:This question focuses on Java’s checked exceptions and resource cleanup. Since FileOutputStream.close() declares throws IOException, calling it must be handled or declared. The code calls close() in finally without handling it.
Given Data / Assumptions:
- Every method of
FileOutputStream, includingclose(), can throwIOException. finallyexecutes whether or not an exception occurs.- There is no nested try/catch around
out.close(), andmaindoes not declarethrows IOException.
Concept / Approach:Checked exceptions must be either caught or declared. The compiler flags the call to out.close() as an unhandled checked exception. Additionally, out could be null if the constructor fails, but the compilation error is about the unhandled exception, not a NullPointerException (which would be a runtime concern).
Step-by-Step Solution:
Identify problem line: thefinally block calls out.close().Since close() declares throws IOException, wrap it in a try/catch or test for null and handle exceptions.Without handling, compilation fails at this line.Verification / Alternative check:Fix by using try-with-resources or by writing finally { if (out != null) { try { out.close(); } catch(IOException e) { / handle */ } } }.
Why Other Options Are Wrong:
- Earlier lines are fine; the constructor and write are already inside a try/catch that handles
IOException. - Claiming successful compilation ignores the checked-exception rule for the
finallyblock.
Common Pitfalls:Assuming code in finally does not need its own exception handling; it does.
Final Answer:This program fails to compile due to an error at line 18.