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

When Finally Runs

Exploring the exact execution order of finally with returns, throws, and normal exits.

When Finally Runs

You'll learn the exact order in which finally executes, even when there are returns, throws, or normal exits in your try/catch blocks.

Execution Order Demystified

The finally block is JavaScript's most persistent code — it runs no matter what happens in try or catch. But when exactly does it run? Understanding the timing is crucial for writing predictable error handling.

Finally Runs Last, But Before Leaving

Think of finally as a security checkpoint at an airport exit. No matter how you got to the exit (normal boarding, emergency evacuation, or being escorted out), you must pass through that checkpoint before leaving the building.

Here's what happens in different scenarios:

function normalExit() {
  try {
    console.log("Try block");
    return "Exiting normally";
  } finally {
    console.log("Finally runs before return");
  }
}

normalExit();
// Output:
// Try block
// Finally runs before return
function errorExit() {
  try {
    throw new Error("Something broke");
  } catch (error) {
    console.log("Caught error");
    return "Handled";
  } finally {
    console.log("Finally runs even after catch return");
  }
}

errorExit();
// Output:
// Caught error
// Finally runs even after catch return
function uncaughtError() {
  try {
    throw new Error("Unhandled");
  } finally {
    console.log("Finally runs before error propagates");
  }
}

The Key Point

Finally executes after the try or catch block's code completes, but before any return value is actually returned or any error is propagated up the call stack. It's JavaScript's way of guaranteeing cleanup happens at the last possible moment.

Key Takeaway: The finally block always runs after try or catch completes but before control leaves the function — even when there's a return statement or an unhandled error.