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

Throwing vs Returning Error Values

Compare the throw approach with returning error values and when each pattern is appropriate.

Throwing vs Returning Error Values

You'll learn when to throw errors versus returning error values, and how to choose the right pattern for your situation.

Two Approaches to Signaling Failure

When something goes wrong in your code, you have two main options:

  1. Throw an error — immediately halt execution and jump to the nearest catch block
  2. Return an error value — return a special value (like null, undefined, or an error object) that the caller must check

Think of throwing like pulling a fire alarm—it stops everything and demands immediate attention. Returning an error value is like raising your hand in class—the flow continues, but someone needs to notice and respond.

When to Throw Errors

Use throw when:

  • The error is exceptional and unexpected (like a network failure or invalid input)
  • Recovery isn't possible at the current level
  • You want to force the caller to handle the problem
function divide(a, b) {
  if (b === 0) {
    throw new Error('Cannot divide by zero');
  }
  return a / b;
}

When to Return Error Values

Return error values when:

  • Failure is a normal, expected outcome (like a search finding no results)
  • The caller can easily handle the error inline
  • You want flexibility—the caller can choose to ignore it
function findUser(id) {
  const user = database.get(id);
  return user || null; // null indicates "not found"
}

Making the Choice

Ask yourself: "Is this situation truly exceptional, or just one possible outcome?" A missing file might deserve a throw, but an empty search result probably doesn't.

Key Takeaway: Throw errors for exceptional failures that interrupt normal flow; return error values for expected, recoverable outcomes that are part of normal operation.