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

The Finally Block

Understanding finally's guarantee to execute cleanup code regardless of success or failure.

The Finally Block

You'll learn how finally ensures cleanup code always runs, whether your try succeeds or fails.

What Is the Finally Block?

The finally block is an optional third part of a try...catch statement. It contains code that will always execute, no matter what happens in the try or catch blocks — even if an error is thrown, caught, or if a return statement is hit.

Think of finally like the closing credits of a movie: no matter how the movie ends (happy, sad, or confusing), the credits always roll.

Why Finally Matters

Sometimes you need to perform cleanup tasks — closing files, releasing resources, hiding loading spinners — that must happen regardless of success or failure. Without finally, you'd have to duplicate that cleanup code in both the try and catch blocks. finally gives you one guaranteed place to put it.

How It Works

try {
  console.log("Attempting operation...");
  // risky code here
} catch (error) {
  console.log("Error caught:", error.message);
} finally {
  console.log("Cleanup always runs!");
}

The finally block executes:

  • After the try block if no error occurs
  • After the catch block if an error was caught
  • Even if the try or catch contains a return statement
function test() {
  try {
    return "success";
  } finally {
    console.log("This runs before the return!");
  }
}

test(); // Logs "This runs before the return!", then returns "success"

Key Takeaway: Use finally to guarantee cleanup code runs, providing a safety net for essential operations that must execute regardless of errors or early returns.