Throwing vs Returning Errors
You'll learn: When to throw errors versus returning error objects, and how each pattern affects your code design.
Two Ways to Signal Failure
When something goes wrong in your function, you have two choices: throw an error (which stops execution and propagates up the call stack) or return an error object (which lets the caller decide what to do next).
Think of throwing like pulling a fire alarm—execution stops immediately and control jumps to the nearest catch block. Returning an error is like handing someone a note that says "this didn't work"—they can read it and decide their next move.
When to Throw Errors
Throw errors when:
- The problem is unexpected and the function cannot reasonably continue
- You want to enforce preconditions (invalid arguments, violated contracts)
- Exceptional circumstances occur (network failures, missing resources)
function divide(a, b) {
if (b === 0) {
throw new Error('Cannot divide by zero');
}
return a / b;
}
When to Return Errors
Return error objects when:
- Failure is a normal, expected outcome (user not found, validation failed)
- You want explicit error handling at the call site
- You're building functional-style code that avoids side effects
function findUser(id) {
const user = database.get(id);
if (!user) {
return { error: 'User not found', code: 'NOT_FOUND' };
}
return { data: user };
}
The Trade-off
Throwing makes error handling mandatory (uncaught errors crash), while returning makes it optional (callers can ignore errors). Choose throwing for truly exceptional cases and returning for predictable failure modes.
Key Takeaway: Throw errors for exceptional conditions that should stop execution; return error objects for expected failures that callers should handle explicitly.