Java Close the Resource You Own
Try-with-resources gives a scoped resource an automatic close operation. It is preferable to hand-written cleanup that can accidentally skip a close when another statement fails.
Understand the idea
A resource must implement AutoCloseable. Resources are closed in reverse declaration order. If the body throws and closing also fails, the primary failure is preserved and close failures may be suppressed. Closing a resource you do not own, such as a stream supplied by a caller for reuse, can violate a larger application contract. Establish ownership before deciding where the scope ends.
Run it locally
Use a local JDK 21 or newer. Save the complete example as Main.java in a separate lab folder, then compile and run it with the commands below. Java examples do not run in Bhylu’s browser playground. The -ea option enables assertion checks used by some lessons.
javac --release 21 -encoding UTF-8 -d out Main.java
java -ea -cp out MainA worked example
import java.io.BufferedReader;
import java.io.StringReader;
public class Main {
public static void main(String[] args) throws Exception {
try (BufferedReader reader = new BufferedReader(new StringReader("Clay\nWood\n"))) {
System.out.println(reader.readLine());
System.out.println(reader.readLine());
}
}
}
Expected output
Clay
WoodThe buffered reader is created and owned by this method. It closes when the try block finishes, including if a read throws. StringReader keeps the example self-contained while demonstrating the same ownership pattern used for a file reader. Declaring throws Exception keeps this small main focused; a library method should generally declare the more specific failure it exposes.
Check the official Java documentation for detailed contracts and supported options.