JavaScript throw

Beginner
5 min read
Updated: Nov 2026
3 examples

Definition and Usage

throw stops normal flow and raises a value—usually an Error—to the nearest catch or to the runtime if nothing catches it.

JavaScript Syntax

JavaScript
try {
  throw new Error("boom");
} catch (err) {
  console.log(err.message);
}
Try it Editor

How It Works

  1. throw creates an Error.
  2. catch receives it. message is "boom".

Examples

Example 1 — Throw a TypeError

Pick a subclass that describes the problem.

JavaScript
try {
  throw new TypeError("need number");
} catch (err) {
  console.log(err.name);
}
Try it Editor

How It Works

  1. TypeError.name is "TypeError".
  2. See Error Types for more subclasses.

Example 2 — Validate arguments

Fail fast on bad input.

JavaScript
function square(n) {
  if (typeof n !== "number") throw new TypeError("n");
  return n * n;
}
console.log(square(3));
Try it Editor

How It Works

  1. Valid number returns 9.
  2. Bad types would throw.

Example 3 — Prefer Error objects

Avoid throw "string" — you lose stack traces.

JavaScript
try {
  throw new Error("use Error");
} catch (err) {
  console.log(err instanceof Error);
}
Try it Editor

How It Works

  1. Error instances work with instanceof.
  2. They carry message and stack.

Frequently Asked Questions

Throw Error (or a subclass). Avoid bare strings or numbers.
In a try...catch, or an async function’s catch / .catch on a Promise.

CODETOFUN NEWS

Stay Ahead in Tech

Get the latest IT news, programming updates, and technology trends directly on your phone.

Your daily dose of tech, straight to your feed.

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

6 people found this page helpful