liveBook · Manning

Finally

As explained in JavaScript in Depth

A JavaScript control-flow block that executes after try-catch processing regardless of whether an exception occurs.

Use a finally block to run cleanup after try-catch processing, whether an error was thrown, caught, or not thrown. It provides a cleanup point for operations such as a transaction, where cleanup belongs at the boundary of the whole operation. section 7.5 section 7.5

A return or throw inside finally can suppress or replace an error already in flight. The original error may still exist, but its recovery and debugging context is lost. Avoid using finally to return values or throw new errors carelessly. section 7.5 section 7.6

function suppressed() {
  try {
    throw new Error("This disappears");
  } finally {
    return "Success!";  #A
  }
}
 
function replaced() {
  try {
    throw new Error("This disappears");
  } finally {
    throw new Error("This replaces it");
  }
}
 
 
console.log(suppressed());  #B
console.log(replaced());  #C

Compare a finally block that returns over a pending error with one that throws a replacement error. section 7.5

How JavaScript in Depth covers it

How deep it goes
Defines guaranteed execution and demonstrates error suppression or replacement, without detailing engine internals.
Examples
Demonstrates database transaction handling and finally blocks that suppress or replace pending errors.
What you can do after
Evaluate cleanup behavior and avoid finally statements that suppress or replace errors.
How it connects
Connects finally to try-catch, exception propagation, resource cleanup, and transaction boundaries.

Also explained in

Compare how 4 books explain finally →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of JavaScript in Depth. The section links point to the parts of the book it draws on.