liveBook · Manning

Catch block

As explained in JavaScript in Depth

A mechanism or code path that intercepts and responds to errors.

A catch clause determines whether an exception stops at a local recovery point or continues unwinding the call stack. When code inside a try block throws, the engine searches upward through stack frames until it finds a matching catch handler or reaches the host runtime. section 7.5

The catch clause handles errors thrown within the try block’s lexical scope. Catching stops propagation, but placement changes what the handler can do: a deep handler retains local debugging context, while a higher handler may have better information for recovery decisions. section 7.5

Use catch clauses with these boundaries in mind:

  • Treat uncaught errors as host-dependent: browsers may log them, while Node.js may log the error and terminate the process. section 7.5
  • Do not expect a surrounding synchronous catch to intercept an exception thrown later by an asynchronous callback. section 7.5
  • Use a catch clause at a semantic boundary where the available context supports a recovery or debugging decision. section 7.0 section 7.5

Rollback, then preserve the cause

A transaction boundary can catch a database failure, roll back the transaction, and throw a new error with the original error as its cause. Recovery happens locally while the failure remains available for higher-level diagnosis. 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
  }
}

Shows nested catch clauses: the inner handler intercepts the error, so the outer handler is never reached. section 7.5

How JavaScript in Depth covers it

How deep it goes
Explains lexical scope, stack unwinding, placement tradeoffs, and asynchronous limits, while deferring engine-specific implementation details.
Examples
Uses nested functions, database transactions, asynchronous timers, browser error events, and Node.js process handlers.
What it assumes
Assumes functions, lexical scope, and call stacks while teaching error propagation and host-specific uncaught behavior.
What you can do after
Diagnose propagation and place catch clauses where available context supports recovery, rollback, or debugging.
How it connects
Connects try-catch to call stacks, lexical scope, error propagation, asynchronous operations, stack traces, and host runtimes.

Also explained in

Compare how 3 books explain 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.