liveBook · Manning

Try-catch block

As explained in JavaScript in Depth

A JavaScript control-flow construct that executes protected code and handles exceptions thrown from it in a catch handler.

Why does a catch handler miss an error thrown by a function it called? If that function schedules a setTimeout callback, the try block finishes before the callback runs. The callback executes on a later call stack, outside the handler’s reach. A surrounding try-catch handles synchronous propagation, not errors from work scheduled to run later. section 7.5

When an error is thrown, normal execution stops and the engine unwinds the call stack frame by frame, looking for a catch handler. A handler around a function call can therefore catch an error thrown deeper in that synchronous call chain. Once caught, propagation stops; an outer catch does not run unless the error is thrown again. section 7.5

function deep() {
  throw new Error("Deep error");
  console.log("Never executed");
}
 
function middle() {
  try {
    deep();
  } catch (e) {
    console.log("Caught in middle");  #A
     }
}

function outer() {
  try {
    middle();
  } catch (e) {
    console.log("Never reached");  #B
  }
}

The error starts in deep(), but middle() catches it. Its outer caller never reaches its own handler. section 7.5

Catch where a recovery decision is possible and useful debugging context remains. A handler beside an individual database query may be too early to decide whether to roll back; one at the application’s top level may be too late to retain the operation’s meaning. Transaction, API, resource, and user-operation boundaries are practical candidates. section 7.5

function updateUserProfile(userId, changes) {
  const tx = db.beginTransaction();
  try {
    const user = tx.query('SELECT * FROM users WHERE id = ?', userId);  #A
    tx.query('UPDATE users SET ... WHERE id = ?', userId, changes);  #A
    tx.query('INSERT INTO audit_log ...', userId, changes);  #A
    tx.commit();
  } catch (e) {
    tx.rollback();  #B
    throw new Error('Profile update failed', { cause: e });  #C
  }
}

The transaction handler rolls back the whole profile update, then wraps the error with cause to preserve the original failure. section 7.5

A finally block runs during cleanup, but a return or throw inside it can suppress or replace the original error. Avoid turning cleanup into an accidental change of outcome. If no catch handles an error, the host runtime decides what happens: a browser may log it, while Node.js may log it and terminate the process. Global handlers are a safety net, not a substitute for catches at useful boundaries. section 7.5 section 7.6

Try-catch is not inherently a V8 optimization barrier. A function can be optimized while its catch branch remains unexecuted, then deoptimize when that previously unseen branch runs. Creating Error objects has a separate cost: each records stack-frame information, even if its stack string is never read. Treat those costs as distinct from the syntax itself. section 7.4.1

Rule of thumb: catch synchronous failures at a boundary that can act on them, preserve their cause when adding context, and do not expect a surrounding try-catch to follow work across a timer callback. Promises and async/await provide different propagation mechanisms for asynchronous operations. section 7.5 section 7.6

How JavaScript in Depth covers it

How deep it goes
Explains stack unwinding, handler placement, and timer-callback limits; defers asynchronous propagation through Promises and async/await.
Examples
Uses nested function calls, a database transaction, a timer callback, and a previously unexecuted V8 catch branch.
What you can do after
Diagnose/debug with it by identifying which handler can catch a failure and where recovery belongs.
How it connects
Connects try-catch to call stacks, error causes, finally blocks, global error handlers, and asynchronous error propagation.

Also explained in

Compare how 12 books explain try-catch block →

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.