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

Exceptions in close()

Handling exceptions thrown by close() and understanding checked vs unchecked exceptions.

Exceptions in close()

You'll learn how to handle exceptions that close() might throw and why this matters for resource cleanup.

The Problem with close() Failures

When you implement the close() method from AutoCloseable, you need to decide what happens if cleanup fails. The close() method is allowed to throw exceptions — but should it throw checked or unchecked exceptions? This choice affects how callers handle your resource.

Checked vs Unchecked in close()

When close() declares a checked exception (like IOException), callers must handle it. This can be awkward: you're already done with the resource, but now you have to catch an exception during cleanup.

When close() throws an unchecked exception (like IllegalStateException), callers aren't forced to handle it. This is cleaner for most cases but means failures might go unnoticed.

// close() with checked exception
public void close() throws IOException {
    if (stream != null) {
        stream.close(); // may throw IOException
    }
}

// close() with unchecked exception
public void close() {
    if (isClosed) {
        throw new IllegalStateException("Already closed");
    }
    // cleanup logic
}

Best Practice Guidelines

  • If cleanup failure is critical and recoverable (like a database commit failure), use a checked exception
  • If cleanup is best-effort or indicates a programming error, use an unchecked exception or swallow the error
  • Document what your close() method throws and why

Think of it like closing a door: sometimes you need to know if the lock failed (checked), but usually you just want to move on (unchecked).

Key Takeaway: The close() method can throw exceptions; choose checked exceptions for recoverable failures and unchecked for programming errors or when cleanup failure isn't critical.