Learn JavaScript
❯ errors_modules.throwing

throwing Errors in JavaScript

$concept

throw launches any value up the stack to the nearest matching catch — but only Error objects (with message, name, and stack traces) debug sanely. throw "oops" works yet strands responders without stacks or types; throw new Error("oops") carries both.

Throw for programmer-facing contract violations (invalid arguments, impossible states); return error values or Results for expected failures (missing records, validation). Sync throws unwind immediately; async throws become rejections caught by await-try or .catch.

$how it works
1

Throw Errors, not values

throw new Error("msg") — stacks, names, and instanceof checks versus bare strings' nothing.

2

Contracts throw, flows return

Violated preconditions and impossible states throw; expected absences (not found) return null/undefined or Results.

3

Sync unwinds now

throw exits all frames to the nearest try — code after it in the block never runs.

4

Async throw rejects

Throws inside async functions and .then callbacks become rejections — handled by await-try or terminal .catch.

$example
function divide(a, b) {
if (b === 0) throw new Error("divide by zero");
return a / b;
}
try {
divide(1, 0);
} catch (e) {
console.log("caught:", e.message);
}
Output
caught: divide by zero
1The zero denominator violates the contract — throw launches an Error carrying the message and stack.
2Unwinding skips the division and lands in catch with e.message intact.
3caught: divide by zero prints — contract violation reported with location.
$use cases
Precondition enforcement (non-null, in-range) at API entries
Impossible-state guards that should never fire (but prove it if they do)
Error objects exclusively — never bare strings or numbers
Expected failures modeled as return values, not throws

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Re-implement each visualized algorithm in JavaScript yourself — building beats watching.