memory (heap)call stackname"RangeError"message"n < 0"global frameroot framen = 91function root(n) {2 if (n < 0) throw new RangeError("n < 0");3 return Math.sqrt(n);4}5try {6 console.log(root(9));7 console.log(root(-4));8 console.log("not reached");9} catch (err) {10 console.log(err.name, err.message);11} finally {12 console.log("done");13}Console3root.js:6RangeError n < 0root.js:10doneroot.js:12✕ Uncaught RangeError: n < 0throw RangeError3
Right: the call stack, one frame per running call; back: the Error object in memoryLeft: the script root.js; front: the consoleTokens: instructions, a returned value, and the thrown error falling down the stackFront left, the script root.js; behind it, memory, where the Error object appears. On the right, the call stack: the global frame at the bottom, and the root frame piled on top while root runs. In front, the developer console. throw stops root and sends the error down the stack: root's frame pops, and the search stops at the global frame because it is inside a try. catch receives the error; finally runs last. The stack property is not yet part of the ECMAScript standard, but every major engine adds it to Error objects. Its text differs between engines.

Exceptions

  1. Statements normally run one after another. throw breaks that flow: it stops the running function at once and hands a value, usually an Error object, back down the call stack. If no code catches it, the script stops.

A normal call

Throw and catch

Uncaught and built-in errors

What happens

// step 1/11 · flow
call stack  one frame per function call still running
            the script itself is the bottom frame
throw x     stop now and pass x down the stack
try/catch   a place where it can be caught
no catch    the script stops: "uncaught" error

throw accepts any value, even a number or a string, but throwing an Error object is the convention: it carries a name, a message and a stack trace, and err instanceof Error is true. The figure draws the call stack as boxes. The specification calls each frame an execution context; the engine pushes one per function call and pops it when the call returns or is abandoned by a throw.