Skip to content

JavaScript Tutorial Error Handling

Throwing Errors in JavaScript

Lesson 160 of 258 2 min read By Deepak Paswan Updated Oct 4, 2026

You can throw an error yourself when something is wrong and your function cannot continue.

script.js
JS
function divide(a, b) {
  if (b === 0) {
    throw new Error("Cannot divide by zero");
  }
  return a / b;
}

try {
  console.log(divide(10, 2)); // → 5
  console.log(divide(1, 0));
} catch (error) {
  console.log("Error:", error.message); // → Error: Cannot divide by zero
}

throw stops the function immediately and passes the error up to the nearest catch.

Throw Error objects

JavaScript lets you throw anything, even a string or a number. Always throw Error objects. They carry a stack trace that shows where the problem occurred, and they work with tools and instanceof.

script.js
JS
throw "something went wrong";             // legal, but bad: no stack trace
throw new Error("something went wrong"); // good

Validating input

Throwing is a good way to reject invalid arguments early.

script.js
JS
function setAge(age) {
  if (typeof age !== "number" || Number.isNaN(age)) {
    throw new TypeError("Age must be a number");
  }
  if (age < 0 || age > 150) {
    throw new RangeError("Age must be between 0 and 150");
  }
  return age;
}

for (const input of [30, -5, "abc"]) {
  try {
    console.log("OK:", setAge(input));
  } catch (error) {
    console.log(`${error.name}: ${error.message}`);
  }
}

The cause option

When you catch an error and throw a new one with a friendlier message, keep the original in cause.

script.js
JS
function loadConfig(text) {
  try {
    return JSON.parse(text);
  } catch (error) {
    throw new Error("Invalid configuration file", { cause: error });
  }
}

try {
  loadConfig("{oops");
} catch (error) {
  console.log(error.message);          // → Invalid configuration file
  console.log(error.cause.name);       // → SyntaxError
}

Where an error goes

If nothing catches it, the error travels up through the calling functions, and if it reaches the top, the browser prints it in the console and the current task stops.

script.js
JS
function a() { b(); }
function b() { throw new Error("from b"); }

try {
  a();
} catch (error) {
  console.log(error.message); // → from b
}

Throw or return?

SituationBetter
A programmer made a mistake (wrong argument type)throw
Something unexpected stopped the workthrow
An expected outcome (“not found”, “no match”)return null or undefined
User typed invalid datavalidate and show a message, do not throw
info
Rethrowing
Inside a catch, you can throw error again if you cannot handle it. That lets a higher level deal with it.