1Z0-830 practice question 10 of 25

Which of the following code snippets correctly handles a potential IOException thrown while reading a file?

Full set: 116 questions
Answer options
A:

A. ```java String data = readFile("myfile.txt"); System.out.println(data);

B:

B. ```java try { String data = readFile("myfile.txt"); System.out.println(data); } catch (Exception e) { System.out.println("Error reading file"); }

C:

C. ```java try (FileReader reader = new FileReader("myfile.txt")) { int data = reader.read(); System.out.println((char) data); }

D:

D. ```java String data = readFile("myfile.txt"); catch (IOException e) { 13/97 System.out.println("Error reading file"); } // Compile time error: catch block without try block

Correct Answer:
[C]
Explanation

The try-with-resources statement, introduced in Java 7, is the recommended and most correct way to handle resources that must be closed, such as file streams. It ensures that the resource (in this case, FileReader) is automatically closed at the end of the statement, regardless of whether the try block completes normally or throws an exception. This prevents resource leaks, a common source of errors in I/O operations. The IOException from new FileReader() or reader.read() is handled implicitly by this structure, which must be enclosed in a method that either catches or declares the exception.

Why Incorrect

A. This snippet shows no exception handling mechanism. It would not compile if the readFile method is declared to throw a checked IOException.
B. While this try-catch block is syntactically valid, it catches the overly broad Exception and, more importantly, does not show the resource being closed, risking a resource leak.
D. This code is syntactically incorrect. A catch block must always be preceded by a try block. It will result in a compile-time error.

References

1. Oracle Corporation. (n.d.). The Java™ Tutorials

Essential Java Classes

The try-with-resources Statement. Oracle Help Center. This tutorial explicitly states it "is a try statement that declares one or more resources... and ensures that each resource is closed at the end of the statement." Retrieved from https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html

2. Gosling

J.

Joy

B.

Steele

G.

Bracha

G.

& Buckley

A. (2014). The Java® Language Specification

Java SE 8 Edition. Addison-Wesley Professional. Section 14.20.3

"try-with-resources".

Scroll to Top