Skip to content
Tutorials Center
My learning

Topics

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.

JavaScript
throw new Error("Something went wrong");

Try it

JS Throw and catch

Press Run (or Ctrl + Enter) to see the console output here.

No output.

JS A custom error class

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Syntax

JavaScript
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 expect Error instances.
  • Choose the right type. TypeError for wrong kinds of values, RangeError for values outside an allowed range, SyntaxError for 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 throw inside an async function or a .then() callback rejects the resulting promise instead of unwinding the caller's stack. Use await inside try...catch or .catch() to handle it.
  • Callbacks that run later (for example in setTimeout) are outside the original try block, so a throw there cannot be caught by it.
  • Throw expressions. There is no throw expression 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.