Encodera

Thanks for reading!

Donate to the site — we work hard for you.

JavaScript reference

throw

Throws an error and stops the function.

Available since: ES3

Syntax

throw expression

Examples

Checking an argument:

function divide(a, b) {
  if (b === 0) {
    throw new Error('Division by zero');
  }
  return a / b;
}
 
try {
  console.log(divide(10, 2));
  console.log(divide(1, 0));
} catch (error) {
  console.log(error.message);
}

Output:

5
Division by zero

Rethrowing an error you do not handle:

function parse(text) {
  try {
    return JSON.parse(text);
  } catch (error) {
    if (error instanceof SyntaxError) return null;
    throw error;
  }
}
 
console.log(parse('{bad'));

Output:

null

Notes

You can throw anything, even a string, but it is customary to throw Error objects or subclasses: they have name, message and stack.

See also

  • try...catch — Catches errors so the program does not stop.
  • Error — The base error class: created and thrown with throw.
  • Error.prototype.cause — The original reason for an error — so it is not lost when rethrowing.

In the tutorial

  • Errors and try...catch — Error handling in JavaScript: try, catch and finally blocks, the error object, the throw statement and built-in error types.

Thanks for reading!

Donate to the site — we work hard for you.