Course contentsShow
← Java
Lesson 837 of 2,87020. Try-With-Resources and Resource ManagementFree lesson

Resource Initialization Failures

If resource initialization throws, no close() is called; handle with surrounding try-catch if needed.

Resource Initialization Failures

You'll learn: What happens when a resource fails to initialize in a try-with-resources statement, and how to handle it properly.

When you declare a resource in a try-with-resources statement, that resource must be successfully created before the try block executes. If the initialization itself throws an exception, the close() method is never called because the resource was never fully established.

The Critical Moment

Think of it like buying a ticket to enter a theme park. If your credit card is declined at the ticket booth (initialization fails), you never get inside—so there's nothing to "exit" from later. Similarly, if a resource constructor or factory method throws an exception, there's no resource object to clean up, so close() doesn't run.

Why This Matters

try (FileInputStream fis = new FileInputStream("missing.txt")) {
    // If FileInputStream constructor throws FileNotFoundException,
    // we never enter this block, and close() is never called
    // (because fis was never successfully created)
}

If "missing.txt" doesn't exist, the FileInputStream constructor throws a FileNotFoundException during initialization. Since the resource wasn't successfully created, there's nothing to close.

Handling Initialization Failures

If you need to catch initialization exceptions specifically, wrap the try-with-resources in an outer try-catch:

try {
    try (FileInputStream fis = new FileInputStream("file.txt")) {
        // Use resource
    }
} catch (FileNotFoundException e) {
    // Handle initialization failure
    System.out.println("File not found during initialization");
}

The outer catch block handles exceptions thrown during resource creation, while try-with-resources handles cleanup if initialization succeeds.

Key Takeaway: If resource initialization throws an exception, close() is never called because no resource was created; use a surrounding try-catch to handle initialization failures separately from resource usage errors.