What is the difference between throw and return in error handling

· Category: JavaScript

Short answer

throw interrupts normal control flow and propagates up the call stack until caught, while return gives control back to the caller with a value.

Key differences

Aspect throw return
Control flow Unwinds stack Resumes caller
Requires catch Yes No
Stack trace Yes No
Use case Unexpected failures Expected outcomes

When to use each

  • Throw for programming errors, invalid state, or broken invariants.
  • Return for normal outcomes, including sentinel values like null for "not found."

Example

function divide(a, b) {
  if (b === 0) throw new Error("Division by zero");
  return a / b;
}

try {
  console.log(divide(4, 0));
} catch (err) {
  console.error(err.message);
}

Why it matters

Overusing throw for expected cases makes control flow jumpy and hard to follow. Reserve exceptions for truly exceptional situations.