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

The close() Method Contract

Exploring the close() method signature, exceptions, and idempotency requirements.

The close() Method Contract

What you'll learn: You'll understand the rules and expectations for implementing the close() method in classes that use the AutoCloseable interface.

Understanding the Contract

When you implement AutoCloseable, you're promising to follow specific rules for your close() method. These rules form a "contract" that ensures your resource management works reliably with try-with-resources statements.

The Method Signature

The close() method must be declared as:

void close() throws Exception

While throws Exception is the signature in AutoCloseable, you can (and usually should) declare a more specific exception type that's meaningful for your resource.

Key Requirements

Idempotency: Your close() method should be idempotent, meaning calling it multiple times produces the same result as calling it once. After the first close, subsequent calls should do nothing or be harmless.

// Good: Safe to call multiple times
public void close() {
    if (connection != null) {
        connection.disconnect();
        connection = null; // Prevents double-close issues
    }
}

Exception Handling: If close() fails, it should throw an exception to signal the problem. However, exceptions from close() can suppress exceptions from the try block, so avoid throwing exceptions unnecessarily.

Resource Release: The method must release all resources held by the object—file handles, network connections, database connections, etc.

Think of It Like...

Imagine closing a door. You can pull the handle multiple times after it's closed—it doesn't break the door. And if the door is stuck, you should signal that problem (throw an exception) rather than silently pretending it closed.

Key Takeaway: The close() method must safely release resources, be idempotent (safe to call multiple times), and declare appropriate exceptions—this contract ensures predictable resource cleanup.