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 questionsThe 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.
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.
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".
Keep practicing
Take the free 1Z0-830 practice test
Ten exam-style questions with answers and explanations, plus the exam facts and study guides.
More questions
Other 1Z0-830 practice questions
- Question 1A consumer needs to access a service provided by another module. Which of the following s…
- Question 2Which of the following statements is TRUE about modules in Java SE 21?
- Question 3What interface does a class need to implement to be eligible for serialization?
- Question 4What is the primary benefit of encapsulation in Java?
- Question 5A Path object represents which of the following?
- Question 6Which of the following statements about overloaded methods with varargs is TRUE?
