JavaScript Reference ยท Statements and Declarations
The throw statement
Reference for the JavaScript throw statement: throwing Error objects, custom error classes, what happens to uncaught exceptions and why to avoid throwing strings.
The throw statement raises an exception. Execution of the current function stops immediately, and the engine unwinds the call stack until it finds a catch block that can handle the value. If nothing catches it, the error is reported as uncaught: the console prints it, and in a script the current task ends; in Node.js an uncaught exception terminates the process.
You can throw any value, but you should almost always throw an Error object (or a subclass), because it carries a message and a stack trace.
throw new Error("Something went wrong");
Try it
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Syntax
throw expression;
| Part | Description |
|---|---|
expression |
The value to throw. Usually an Error instance. |
Exceptions: throw itself does not fail; the thrown value is the exception. A line break between throw and its expression is a syntax error.
Usage notes
- Throw Error objects.
throw "oops"works, but a string has no stack trace and cannot be told apart by type. Debuggers and error reporters expectErrorinstances. - Choose the right type.
TypeErrorfor wrong kinds of values,RangeErrorfor values outside an allowed range,SyntaxErrorfor bad syntax, or your own subclass for domain errors. - Add context.
new Error("message", { cause: originalError })keeps the original error attached when you wrap it. - Rethrowing. Inside
catch,throw err;passes an error you cannot handle to the next handler. Check the type first and rethrow what you do not recognize. - Promises and async functions. A
throwinside anasyncfunction or a.then()callback rejects the resulting promise instead of unwinding the caller's stack. Useawaitinsidetry...catchor.catch()to handle it. - Callbacks that run later (for example in
setTimeout) are outside the originaltryblock, so a throw there cannot be caught by it. - Throw expressions. There is no
throwexpression yet; to throw inside an expression, call a helper function that throws. - Performance. Exceptions are for exceptional cases, not normal control flow such as "key not found" in a loop.
Browser support
throw works in every JavaScript engine. The cause option of Error is available in current browsers; check a compatibility table for older ones.