throw

Raises a user-defined exception, transferring control to the nearest catch.

Since ES3 Spec ↗

Syntax

throw expression;

Examples

function check(n) {
  if (n < 0) throw new Error("must be non-negative");
  return n;
}
try {
  check(-1);
} catch (e) {
  console.log(e.message);
}
Output
must be non-negative
try {
  throw "plain string";
} catch (e) {
  console.log(typeof e, e);
}
Output
string plain string
class ValidationError extends Error {}
try {
  throw new ValidationError("bad input");
} catch (e) {
  console.log(e.name, e.message);
}
Output
Error bad input

Notes

- You can throw any value, but throwing an `Error` (or a subclass) is strongly recommended for stack traces and consistency. - An uncaught `throw` propagates up the call stack and, if never caught, terminates the current task.

Browser & runtime support

EnvironmentSince version
chrome 1.0
firefox 1.0
safari 1.0
edge 12
node 0.10

See also