Skip to content

Java Try with Resources

But first, let's set the stage. What are resources? Well, think of them as precious items your code borrows temporarily—like a library book or a rental car. These resources need to be returned or cleaned up properly after use to avoid running into trouble later on.

"Try with Resources"— Think of it as your personal assistant, diligently handling the return of borrowed items, all while keeping things spick and span behind the scenes.

So, how does "Try with Resources" work? Picture it as a special block of code wrapped in a "try" statement, followed by a list of resources you want to use. Java takes care of opening and closing these resources automatically, saving you from the hassle of writing extra cleanup code.

Example

java
public class TryWithResourcesExample {
    public static void main(String[] args) {
        try (FileWriter writer = new FileWriter("example.txt")) {
            writer.write("Hello, Try with Resources!");
        } catch (IOException e) {
            System.out.println("Oops! Something went wrong: " + e.getMessage());
        }
    }
}

Isn't that neat? In this example, we're using a FileWriter to write some text to a file. With "Try with Resources", we declare the FileWriter inside the try block. Java automatically takes care of closing the FileWriter when the block ends, even if an exception occurs.

Now, let's add a little personal touch to our journey. Imagine you're planning a camping trip, and you need to borrow some gear from the local outdoor store. With "Try with Resources", it's like having a friendly store clerk who hands you the gear you need and ensures you return it safely when you're done—no fuss, no muss.

Example

Example 1: Without "Try with Resources"

java
import java.io.FileWriter;
import java.io.IOException;

public class WithoutTryWithResourcesExample {
    public static void main(String[] args) {
        FileWriter writer = null;
        try {
            writer = new FileWriter("example.txt");
            writer.write("Hello, without Try with Resources!");
        } catch (IOException e) {
            System.out.println("Oops! Something went wrong: " + e.getMessage());
        } finally {
            try {
                if (writer != null) {
                    writer.close();
                }
            } catch (IOException e) {
                System.out.println("Failed to close the FileWriter: " + e.getMessage());
            }
        }
    }
}

Example 2: With "Try with Resources"

java
import java.io.FileWriter;
import java.io.IOException;

public class WithTryWithResourcesExample {
    public static void main(String[] args) {
        try (FileWriter writer = new FileWriter("example.txt")) {
            writer.write("Hello, with Try with Resources!");
        } catch (IOException e) {
            System.out.println("Oops! Something went wrong: " + e.getMessage());
        }
    }
}
  1. Clarity and Readability:

    • Example 2 (with "Try with Resources") is more concise and readable. The resource (FileWriter) is declared and initialized directly within the try block, making it clear that it will be automatically closed after use.
    • Example 1 (without "Try with Resources") is longer and requires additional code for resource cleanup in the finally block, making it slightly less clear and more prone to errors.
  2. Resource Cleanup:

    • In Example 2, Java automatically closes the FileWriter after the try block finishes, regardless of whether an exception occurs or not. This ensures proper resource cleanup without the need for explicit close statements.
    • In Example 1, resource cleanup is done manually in the finally block, which adds complexity and increases the likelihood of errors, especially in more complex scenarios.
  3. Exception Handling:

    • Both examples handle IOExceptions in a similar manner, printing an error message if an exception occurs.
    • However, Example 2 handles resource cleanup implicitly, reducing the risk of resource leaks and improving code robustness.

Waytojava is designed to make learning easier. We simplify examples for better understanding. We regularly check tutorials, references, and examples to correct errors, but it's important to remember that humans can make mistakes.