Try-With-Resources in Java

Master the try-with-resources statement, AutoCloseable interface, resource management, and handling multiple resources for the OCP 21 exam.

Table of Contents

1. Resource Management Problem

Resources like files, database connections, and network sockets must be properly closed to prevent resource leaks. Traditional try-finally approach is verbose and error-prone.

1.1 Traditional Approach

Example (Verbose):
import java.io.*;
// Traditional approach - verbose and error-prone FileReader file = null;
try {
    file = new FileReader("file.txt");
    // Read file }
catch (IOException e) {
    // Handle exception }
finally {
    if (file != null) {
        try {
            file.close();
        }
    catch (IOException e) {
        // Handle close exception }
} }

1.2 Problems with Traditional Approach

  • Verbose code with nested try-catch blocks
  • Easy to forget closing resources
  • Exception handling becomes complex
  • Resource leaks if close() throws exception

2. AutoCloseable Interface

The AutoCloseable interface (Java 7+) defines resources that can be automatically closed. It has a single method: void close() throws Exception .

2.1 AutoCloseable Interface

Example:
public interface AutoCloseable {
    void close() throws Exception;
} // Closeable extends AutoCloseable (more specific) public interface Closeable extends AutoCloseable {
void close() throws IOException;
// More specific exception
}

2.2 Classes Implementing AutoCloseable

Many Java classes implement AutoCloseable :

  • FileReader , FileWriter
  • InputStream , OutputStream
  • Connection (JDBC)
  • Scanner
  • BufferedReader , BufferedWriter

3. Try-With-Resources Syntax

Try-with-resources (Java 7+) automatically closes resources that implement AutoCloseable .

3.1 Basic Syntax

Syntax:
try (ResourceType resource = new ResourceType()) {
    // Use resource }
catch (ExceptionType e) {
    // Handle exception } // Resource automatically closed
here

3.2 How It Works

  1. Resource is declared and initialized in try parentheses
  2. Resource is used in try block
  3. Resource's close() method is automatically called
  4. Close happens even if exception occurs
  5. Resources are closed in reverse order of declaration

4. Single Resource

4.1 Reading a File

Example:
import java.io.*;
// Try-with-resources - clean and automatic try (FileReader file = new FileReader("file.txt")) {
    int data;
    while ((data = file.read()) != -1) {
        System.out.print((char) data);
    }
} catch (IOException e) {
System.out.println("Error reading file:" + e.getMessage());
} // File automatically closed, even if exception occurs // With BufferedReader try (BufferedReader reader = new BufferedReader( new FileReader("file.txt"))) {
String line;
while ((line = reader.readLine()) != null) {
    System.out.println(line);
}
} catch (IOException e) {
System.out.println("Error:" + e.getMessage());
}

4.2 Writing to a File

Example:
import java.io.*;
// Writing to file try (FileWriter writer = new FileWriter("output.txt")) {
    writer.write("Hello, World!");
}
catch (IOException e) {
    System.out.println("Error writing file:" + e.getMessage());
} // Writer automatically closed // With BufferedWriter try (BufferedWriter writer = new BufferedWriter( new FileWriter("output.txt"))) {
writer.write("Line 1");
writer.newLine();
writer.write("Line 2");
}
catch (IOException e) {
    System.out.println("Error:" + e.getMessage());
}

5. Multiple Resources

Try-with-resources can manage multiple resources. They are closed in reverse order of declaration.

5.1 Multiple Resources Syntax

Example:
import java.io.*;
// Multiple resources - separated by semicolon try (FileReader reader = new FileReader("input.txt");
FileWriter writer = new FileWriter("output.txt")) {
    int data;
    while ((data = reader.read()) != -1) {
        writer.write(data);
    }
} catch (IOException e) {
System.out.println("Error:" + e.getMessage());
} // Both resources automatically closed (writer first, then reader) // Reading from one file, writing to another try (BufferedReader reader = new BufferedReader( new FileReader("input.txt"));
BufferedWriter writer = new BufferedWriter( new FileWriter("output.txt"))) {
    String line;
    while ((line = reader.readLine()) != null) {
        writer.write(line);
        writer.newLine();
    }
} catch (IOException e) {
System.out.println("Error:" + e.getMessage());
}

5.2 Nested Resources

Example:
import java.io.*;
// Nested resources (BufferedReader wraps FileReader) try (BufferedReader reader = new BufferedReader( new FileReader("file.txt"))) {
    // BufferedReader automatically closes FileReader String line = reader.readLine();
}

6. Resource Closing Order

Resources are closed in reverse order of declaration. If an exception occurs during closing, it's suppressed.

Example:
import java.io.*;
// Resources closed in reverse order try (FileReader reader = new FileReader("file1.txt");
// Declared first FileWriter writer = new FileWriter("file2.txt")) {
    // Declared second // Use resources }
catch (IOException e) {
    // Handle exception } // Closing order: writer.close() first, then reader.close() // This is equivalent to: FileReader reader = null;
FileWriter writer = null;
try {
    reader = new FileReader("file1.txt");
    writer = new FileWriter("file2.txt");
    // Use resources }
catch (IOException e) {
    // Handle exception }
finally {
    if (writer != null) {
        try {
            writer.close();
        }
    catch (IOException e) {
    }
} if (reader != null) {
try {
    reader.close();
}
catch (IOException e) {
}
} }

7. Suppressed Exceptions

If an exception occurs in the try block and another exception occurs during resource closing, the closing exception is suppressed and added to the primary exception.

7.1 Accessing Suppressed Exceptions

Example:
import java.io.*;
try (FileReader file = new FileReader("file.txt")) {
    // Exception occurs here throw new RuntimeException("Primary exception");
}
catch (RuntimeException e) {
    System.out.println("Primary:" + e.getMessage());
    // Access suppressed exceptions (from close()) Throwable[] suppressed = e.getSuppressed();
    for (Throwable t : suppressed) {
        System.out.println("Suppressed:" + t.getMessage());
    }
} // If close() throws exception, it's suppressed // Primary exception (from try block) is the main

exception

7.2 Exception Priority

  • Exception from try block is the primary exception
  • Exceptions from close() are suppressed
  • Use getSuppressed() to access suppressed exceptions
  • If no exception in try block, close() exceptions are thrown normally

8. Custom Resources

You can create custom resources by implementing AutoCloseable interface.

8.1 Implementing AutoCloseable

Example:
// Custom resource implementing AutoCloseable class DatabaseConnection implements AutoCloseable {
    private boolean isOpen = true;
    public void executeQuery(String query) {
        if (!isOpen) {
            throw new IllegalStateException("Connection closed");
        }
    System.out.println("Executing:" + query);
}
@Override public void close() throws Exception {
    if (isOpen) {
        System.out.println("Closing database connection");
        isOpen = false;
    }
} } // Using custom resource try (DatabaseConnection conn = new DatabaseConnection()) {
conn.executeQuery("SELECT * FROM users");
}
catch (Exception e) {
    System.out.println("Error:" + e.getMessage());
} // Connection automatically closed // Custom resource with specific exception class FileResource implements AutoCloseable {
@Override public void close() throws IOException {
    // More specific than Exception System.out.println("Closing file resource");
}
}

8.2 Resource with State

Example:
class LockResource implements AutoCloseable {
    private boolean locked = false;
    public void lock() {
        locked = true;
        System.out.println("Lock acquired");
    }
public void unlock() {
    locked = false;
    System.out.println("Lock released");
}
@Override public void close() {
    if (locked) {
        unlock();
    }
} } // Automatic unlock in finally try (LockResource lock = new LockResource()) {
lock.lock();
// Critical section } // Lock automatically
released

9. Exam Key Points

Critical Concepts for OCP 21 Exam:

  • Try-With-Resources: Automatically closes resources implementing AutoCloseable
  • AutoCloseable: Interface with void close() throws Exception
  • Closeable: Extends AutoCloseable, void close() throws IOException
  • Resource Declaration: Resources declared in try parentheses
  • Automatic Closing: close() called automatically, even if exception occurs
  • Multiple Resources: Separated by semicolon, closed in reverse order
  • Closing Order: Last declared resource closed first
  • Suppressed Exceptions: Exceptions from close() are suppressed if try block throws
  • getSuppressed(): Method to access suppressed exceptions
  • Primary Exception: Exception from try block (not from close())
  • Custom Resources: Implement AutoCloseable to create custom resources
  • Resource Scope: Resources are effectively final within try block
  • Cannot Reassign: Resources declared in try-with-resources cannot be reassigned
  • Nested Resources: Inner resources automatically closed when outer closes
  • No Finally Needed: Try-with-resources eliminates need for manual cleanup
  • Exception Handling: Can use catch and finally with try-with-resources
  • Java 7+: Try-with-resources introduced in Java 7
  • Common Resources: FileReader, FileWriter, Scanner, Connection, etc.

Post a Comment

0 Comments