JavaScriptError HandlingBeginner

throw new Error()

Creates and throws a new `Error` object, interrupting the normal flow of execution and signaling an exceptional condition.

Review the syntaxStudy the examplesOpen the coding app
throw new Error(message, [options])

This static page keeps the syntax and examples indexed for search, while the coding app handles interactive exploration and saved references.

What it does

Overview

Creates and throws a new `Error` object, interrupting the normal flow of execution and signaling an exceptional condition.

The `throw` statement is used to raise an exception, and `new Error()` is the standard and recommended way to create an error object in JavaScript. When an `Error` object is thrown, the current function's execution stops immediately, and control is passed up the call stack to the nearest `catch` block. If no `catch` block is found anywhere in the call stack, the program will typically terminate (in Node.js) or the error will be reported to the console as an uncaught exception (in browsers). The `Error` constructor takes an optional `message` string, which provides a human-readable description of the error, and an optional `options` object (since ES2022) which can include a `cause` property for error chaining. Throwing errors is essential for indicating invalid input, unexpected states, failed operations, or other exceptional conditions in your code, allowing callers to handle these situations appropriately. While you can technically throw any JavaScript value (e.g., a string, number, or object), throwing `Error` objects (or custom error types inheriting from `Error`) is a best practice because they automatically provide valuable information like a stack trace, which is crucial for debugging and understanding where the error originated.

Quick reference

Syntax

throw new Error(message, [options])

Inputs

Parameters

message (optional)String · A human-readable description of the error.
options (optional)Object · An optional object that can contain a `cause` property for error chaining.

See it in practice

Examples

1

Throwing a basic error for invalid input

function calculateSquareRoot(num) {
  if (num < 0) {
    throw new Error('Cannot calculate square root of a negative number.');
  }
  return Math.sqrt(num);
}

try {
  console.log(calculateSquareRoot(9));
  console.log(calculateSquareRoot(-4));
} catch (error) {
  console.error('Caught an error:', error.message);
}
Output:
3 Caught an error: Cannot calculate square root of a negative number.

The `calculateSquareRoot` function throws an `Error` if a negative number is passed. The `try...catch` block then intercepts this error and logs its message.

2

Throwing an error with a custom message and name

function validateEmail(email) {
  if (!email.includes('@')) {
    const err = new Error('Invalid email format: missing @ symbol.');
    err.name = 'ValidationError'; // Custom name for error type
    throw err;
  }
  return true;
}

try {
  validateEmail('test@example.com');
  console.log('Email is valid.');
  validateEmail('invalid-email');
} catch (error) {
  console.error(`Error Type: ${error.name}, Message: ${error.message}`);
}
Output:
Email is valid. Error Type: ValidationError, Message: Invalid email format: missing @ symbol.

A custom `name` property is assigned to the `Error` object, allowing for more specific identification of the error type in the `catch` block.

3

Demonstrating the stack trace

function funcC() {
  throw new Error('Error from funcC');
}

function funcB() {
  funcC();
}

function funcA() {
  funcB();
}

try {
  funcA();
} catch (error) {
  console.error('Caught error:');
  console.error(error.stack); // Displays the call stack
}
Output:
Caught error: Error: Error from funcC at funcC (... at funcB (... at funcA (... at <anonymous> (...

When an `Error` object is thrown, it automatically captures the call stack (`error.stack`). This stack trace is invaluable for debugging, showing the sequence of function calls that led to the error.

Debug faster

Common Errors

1

Throwing non-Error objects

Cause: While JavaScript allows `throw` to be used with any value (e.g., `throw 'Something went wrong';`), throwing primitive values or plain objects prevents the error from having a useful stack trace and other standard `Error` properties.

Fix: Always throw instances of `Error` or a class that extends `Error`. This ensures your errors have a `message`, `name`, and crucially, a `stack` property for debugging.

try {
  throw 'A simple string error';
} catch (e) {
  console.error(e); // Outputs 'A simple string error', no stack trace
  // console.error(e.stack); // undefined
}

Runtime support

Compatibility

Node.js, DenoAll modernES1 (throw), ES1 (Error), ES2022 (options.cause)

Source: MDN Web Docs

Common questions

Frequently Asked Questions

Creates and throws a new `Error` object, interrupting the normal flow of execution and signaling an exceptional condition.

message: A human-readable description of the error. options: An optional object that can contain a `cause` property for error chaining.

Throwing non-Error objects: Always throw instances of `Error` or a class that extends `Error`. This ensures your errors have a `message`, `name`, and crucially, a `stack` property for debugging.