JavaScript Error Handling

Understanding try…catch, throw, and Custom Errors

Effective error handling keeps your applications robust and user‑friendly. JavaScript provides several mechanisms to detect, manage, and propagate errors.

1. The try…catch Block

Wrap potentially hazardous code in a try block and handle failures in catch.

try {
  // Code that may throw
  const data = JSON.parse(input);
  process(data);
} catch (err) {
  console.error('Parsing failed:', err);
  alert('Invalid data format! Please check your input.');
}

2. Throwing Errors

Use throw to generate your own error objects.

function divide(a, b) {
  if (b === 0) {
    throw new Error('Division by zero is not allowed.');
  }
  return a / b;
}

3. Custom Error Types

Extend Error to create domain‑specific errors.

class ValidationError extends Error {
  constructor(message) {
    super(message);
    this.name = 'ValidationError';
  }
}

function validate(user) {
  if (!user.email.includes('@')) {
    throw new ValidationError('Invalid email address.');
  }
}

4. Async/Await Error Handling

Combine try…catch with async functions.

async function fetchUser(id) {
  try {
    const response = await fetch(`/api/users/${id}`);
    if (!response.ok) throw new Error('Network response was not ok');
    const user = await response.json();
    return user;
  } catch (err) {
    console.error('Fetch failed:', err);
    throw err; // re‑throw for caller handling
  }
}

5. Interactive Demo

Enter a JSON string below. Errors will be caught and displayed.