codingstuff.io
ExploreTutorialsProblemsCS Subjects
Get Started
ExploreTutorialsProblemsCS Subjects
Get Started
codingstuff.io

Master the art of building software through interactive tutorials, real-world problems, and guided projects.

Pune, Maharashtra, India

codingstuffmail@gmail.com

Product

  • Explore
  • Tutorials
  • Problems
  • CS Subjects

Company

  • About
  • Contact
  • Privacy Policy
  • Terms & Conditions
  • Sitemap

© 2026 codingstuff.io. All rights reserved.

Built with ❤️ for developers everywhere

/
/
All Tutorials
☕

Java Programming

42 / 65 topics
40Java Exceptions41Java Multiple Exceptions42Java try-with-resources
Tutorials/Java Programming/Java try-with-resources
☕Java Programming

Java try-with-resources

Updated 2026-05-12
15 min read

Java try-with-resources

Introduction

In Java, managing resources such as files, database connections, and network sockets is crucial to ensure that they are properly closed after use. Failing to close these resources can lead to resource leaks, which can degrade the performance of your application or even cause it to crash. The try-with-resources statement in Java provides a convenient way to manage resources by ensuring that each resource is closed at the end of the statement.

Core Content

What is try-with-resources?

The try-with-resources statement is a language feature introduced in Java 7 that simplifies exception handling for resources that must be closed after use. It ensures that each resource declared within the try-with-resources block is automatically closed at the end of the block, even if an exception occurs.

AutoCloseable Interface

The try-with-resources statement works with classes that implement the AutoCloseable interface. This interface has a single method:

MethodDescription
void close()Closes the resource and releases any system resources associated with it

Classes such as java.io.FileReader, java.sql.Connection, and java.net.Socket implement the AutoCloseable interface, making them suitable for use in a try-with-resources statement.

Basic Syntax

The basic syntax of the try-with-resources statement is:

Java
1try (ResourceType resource1 = new ResourceType();
2 ResourceType resource2 = new ResourceType()) {
3 // Use resources here
4}; catch (ExceptionType e) {
5 // Handle exceptions here
6}
  • Resource Declaration: Resources are declared in parentheses immediately after the try keyword. Multiple resources can be declared, separated by semicolons.
  • Automatic Closure: Each resource is automatically closed at the end of the try block or when an exception is thrown.

Example 1: Basic Usage

Let's look at a simple example where we use try-with-resources to read from a file:

ReadFile.java
1import java.io.BufferedReader;
2import java.io.FileReader;
3import java.io.IOException;
4
5public class ReadFile {
6 public static void main(String[] args) {
7 try (BufferedReader br = new BufferedReader(new FileReader("example.txt"))) {
8 String line;
9 while ((line = br.readLine()) != null) {
10 System.out.println(line);
11 }
12 } catch (IOException e) {
13 e.printStackTrace();
14 }
15 }
16}

In this example:

  • We declare a BufferedReader resource inside the try-with-resources block.
  • The file is automatically closed after reading its contents or if an exception occurs.
Output
Line 1 of the file
Line 2 of the file
...

Example 2: Multiple Resources

You can declare multiple resources in a single try-with-resources statement. Each resource will be closed in the reverse order of their declaration:

MultipleResources.java
1import java.io.BufferedReader;
2import java.io.FileReader;
3import java.io.IOException;
4
5public class MultipleResources {
6 public static void main(String[] args) {
7 try (BufferedReader br1 = new BufferedReader(new FileReader("file1.txt"));
8 BufferedReader br2 = new BufferedReader(new FileReader("file2.txt"))) {
9 String line;
10 while ((line = br1.readLine()) != null) {
11 System.out.println(line);
12 }
13 while ((line = br2.readLine()) != null) {
14 System.out.println(line);
15 }
16 } catch (IOException e) {
17 e.printStackTrace();
18 }
19 }
20}

In this example:

  • We declare two BufferedReader resources.
  • Both files are closed in the reverse order of their declaration (br2 is closed first, followed by br1).

Example 3: Custom Resource

You can also create your own custom resource by implementing the AutoCloseable interface:

CustomResource.java
1public class CustomResource implements AutoCloseable {
2 public void doSomething() {
3 System.out.println("Doing something...");
4 }
5
6 @Override
7 public void close() throws Exception {
8 System.out.println("Resource closed.");
9 }
10}
UseCustomResource.java
1public class UseCustomResource {
2 public static void main(String[] args) {
3 try (CustomResource resource = new CustomResource()) {
4 resource.doSomething();
5 } catch (Exception e) {
6 e.printStackTrace();
7 }
8 }
9}

In this example:

  • We create a custom CustomResource class that implements AutoCloseable.
  • The resource is automatically closed after performing its task.
Output
Doing something...
Resource closed.

Common Mistakes

  1. Not Implementing AutoCloseable: If a resource does not implement the AutoCloseable interface, it cannot be used in a try-with-resources statement.
  2. Closing Resources Manually: While try-with-resources automatically closes resources, you should still handle exceptions that may occur during closing.

Practical Example

Let's create a practical example where we use try-with-resources to manage multiple database connections:

DatabaseManager.java
1import java.sql.Connection;
2import java.sql.DriverManager;
3import java.sql.SQLException;
4
5public class DatabaseManager implements AutoCloseable {
6 private Connection conn1;
7 private Connection conn2;
8
9 public DatabaseManager() throws SQLException {
10 conn1 = DriverManager.getConnection("jdbc:mysql://localhost/db1", "user", "password");
11 conn2 = DriverManager.getConnection("jdbc:mysql://localhost/db2", "user", "password");
12 }
13
14 public void queryDatabases() throws SQLException {
15 // Perform database queries
16 }
17
18 @Override
19 public void close() throws Exception {
20 if (conn1 != null) conn1.close();
21 if (conn2 != null) conn2.close();
22 }
23}
Main.java
1public class Main {
2 public static void main(String[] args) {
3 try (DatabaseManager dbManager = new DatabaseManager()) {
4 dbManager.queryDatabases();
5 } catch (SQLException e) {
6 e.printStackTrace();
7 }
8 }
9}

In this example:

  • We create a DatabaseManager class that manages two database connections.
  • The connections are automatically closed at the end of the try-with-resources block.

Summary

Key Points
try-with-resources ensures that resources are closed automatically.
Resources must implement the AutoCloseable interface.
Multiple resources can be declared in a single try-with-resources statement.
Custom resources can be created by implementing the AutoCloseable interface.

What's Next?

In the next topic, we will explore how to work with files in Java using classes such as File, FileReader, and FileWriter. Understanding file handling is essential for many applications that require reading from or writing to files.

Stay tuned!


PreviousJava Multiple ExceptionsNext Java Files

Recommended Gear

Java Multiple ExceptionsJava Files