Course contentsShow
← JavaScript
Lesson 1139 of 2,72326. Error HandlingFree lesson

Resource Cleanup Patterns

Using finally for closing connections, releasing locks, and cleaning up resources properly.

Resource Cleanup Patterns

What you'll learn: How to use finally blocks to safely clean up resources like connections, locks, and file handles—even when errors occur.

Why Resource Cleanup Matters

Imagine borrowing a library book. Whether you finish reading it or not, you must return it. In JavaScript, resources like database connections, file handles, or locks work the same way: once opened, they must be closed—regardless of whether your operation succeeds or throws an error.

The Finally Block for Cleanup

The finally block is your cleanup guarantee. It runs after try and catch, no matter what happens—success, error, or even early return.

Basic Pattern

let connection = null;

try {
  connection = openDatabaseConnection();
  // Perform database operations
  const data = connection.query("SELECT * FROM users");
} catch (error) {
  console.error("Database error:", error.message);
} finally {
  // ALWAYS runs, even if error occurs
  if (connection) {
    connection.close();
    console.log("Connection closed");
  }
}

Multiple Resources

let fileHandle = null;
let lock = null;

try {
  lock = acquireLock("user-data");
  fileHandle = openFile("users.txt");
  // Work with file
} catch (error) {
  console.error("Failed:", error.message);
} finally {
  // Clean up in reverse order
  if (fileHandle) fileHandle.close();
  if (lock) lock.release();
}

Why This Matters

Without finally, if an error throws before cleanup code, resources leak. The connection stays open, the lock stays held, memory isn't freed. Finally ensures cleanup happens every single time, making your code reliable and preventing resource exhaustion.

Key Takeaway: Always use finally blocks to clean up resources like connections and locks—it's the only guarantee your cleanup code will run, even when errors occur or early returns happen.