Back
Syntax
Study
Editor
Mode:
HTML
CSS
JavaScript
PHP
Reset
Run »
HTML / CSS / JS
import java.io.*; import java.nio.file.*; public class TryWithResourcesDemo { // Custom AutoCloseable static class ManagedConnection implements AutoCloseable { ManagedConnection(String url) { System.out.println("Opening connection to " + url); } public void query(String sql) { System.out.println("Executing: " + sql); } @Override public void close() { System.out.println("Connection closed"); } } static void readFileDemo(String path) { // Single resource — automatically closed try (BufferedReader reader = new BufferedReader(new FileReader(path))) { String line; while ((line = reader.readLine()) != null) { System.out.println(line); } } catch (IOException e) { System.out.println("Could not read file: " + e.getMessage()); } } static void multipleResources() { // Multiple resources, closed in reverse order try (ManagedConnection conn = new ManagedConnection("db://localhost"); PrintWriter log = new PrintWriter(System.out)) { conn.query("SELECT * FROM users"); log.println("Query completed"); } catch (Exception e) { System.out.println("Error: " + e.getMessage()); } // Both conn and log are closed here automatically } public static void main(String[] args) { multipleResources(); readFileDemo("nonexistent.txt"); // demonstrates catch } }
Result
Open