The JavaScript throw statement
The throw statement raises an error, stopping the current execution and jumping to the nearest catch block (or crashing if there isn't one). Throw an Error object: throw new Error("message"). It's how you signal that something went wrong so calling code can handle it.
Overview
throw raises an error on purpose. When you hit a situation your code can't handle — invalid input, a failed precondition, a missing resource — you throw to signal failure. Execution stops immediately and control jumps to the nearest enclosing catch block; if there isn't one, the error propagates up and, unhandled, crashes that code path.
You can technically throw any value, but you should throw an Error object: throw new Error("Amount must be positive"). Error objects carry a message and a stack trace, which makes debugging far easier than throwing a bare string. There are built-in error types — TypeError, RangeError — and you can subclass Error for your own.
It works hand in glove with try...catch: throw raises, catch handles. In an async function, a throw becomes a rejected promise, caught by try...catch around the await. Throw for exceptional conditions, not ordinary control flow — for an expected "not found", returning null or a result object is usually cleaner than throwing.
Syntax
throw new Error("Something went wrong");
function withdraw(amount) {
if (amount <= 0) {
throw new Error("Amount must be positive");
}
// ...
}
Example
<pre id="out" style="font:15px ui-monospace,monospace"></pre>
<script>
function half(n) {
if (typeof n !== 'number') throw new Error('not a number');
return n / 2;
}
const results = [];
for (const input of [10, 'oops']) {
try { results.push(half(input)); }
catch (e) { results.push('error: ' + e.message); }
}
document.getElementById('out').textContent = results.join('\n'); // 5 / error: not a number
</script>
Best practices
- Throw an
Errorobject (new Error(msg)), not a plain string — it carries a stack trace. - Use specific built-in types like
TypeErrororRangeErrorwhere they fit. - Pair every
throwwith a try...catch somewhere up the call chain. - Reserve throwing for exceptional cases; return a value for expected outcomes like "not found".
Frequently asked questions
How do I throw an error in JavaScript?
throw new Error("message"). Execution stops and jumps to the nearest catch block.Should I throw a string or an Error?
Error object. It includes a message and a stack trace, which a plain string lacks, making errors much easier to debug.What happens if a thrown error isn't caught?
How does throw work with async/await?
throw rejects the returned promise. Catch it with try...catch around the await.