Java I/O (checked exceptions) — will this program compile given that FileOutputStream.close() throws IOException?\n\nimport java.io.;\npublic class MyProgram \n{\n public static void main(String args[])\n {\n FileOutputStream out = null;\n try \n {\n out = new FileOutputStream("test.txt");\n out.write(122);\n }\n catch(IOException io) \n {\n System.out.println("IO Error.");\n }\n finally \n {\n out.close();\n }\n }\n}\n\nChoose the best answer.

Difficulty: Easy

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, including close(), can throw IOException.
  • finally executes whether or not an exception occurs.
  • There is no nested try/catch around out.close(), and main does not declare throws 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: the finally 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 finally block.


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.

Discussion & Comments

No comments yet. Be the first to comment!
Join Discussion