Course contentsShow
← JavaScript
Lesson 1145 of 2,72326. Error HandlingFree lesson

When to Use Specific Error Types

Understand which built-in error type to throw based on the nature of the problem.

When to Use Specific Error Types

You'll learn how to choose the right built-in error type to make your code's problems crystal clear.

Why Error Type Matters

Just like a doctor uses specific terms (headache vs. migraine) to describe different conditions, JavaScript provides specific error types to describe different kinds of problems. Throwing the right error type helps other developers (and your future self) understand what went wrong at a glance.

Matching Error Types to Problems

Each built-in error type signals a specific category of problem:

TypeError – Use when a value is the wrong type or doesn't have an expected method:

function greet(user) {
  if (typeof user !== 'object' || user === null) {
    throw new TypeError('Expected user to be an object');
  }
  return `Hello, ${user.name}`;
}

RangeError – Use when a number is outside its valid range:

function setVolume(level) {
  if (level < 0 || level > 100) {
    throw new RangeError('Volume must be between 0 and 100');
  }
}

ReferenceError – Rarely thrown manually; usually indicates an undefined variable. You might throw it in advanced scenarios where you're implementing custom variable resolution.

SyntaxError – Typically thrown by the parser, but you might throw it when validating user-provided expressions or code strings.

Generic Error – Use for application-specific problems that don't fit the other categories:

function withdraw(amount) {
  if (amount > balance) {
    throw new Error('Insufficient funds');
  }
}

Choose Based on Context

Think about what went wrong: wrong type of data? Use TypeError. Number out of bounds? Use RangeError. Business logic violation? Use Error.

Key Takeaway: Match the error type to the nature of the problem—TypeError for type issues, RangeError for out-of-bounds numbers, and generic Error for application-specific failures.