🚀 LEVEL UP TO SENIOR:Unlock 500+ Advanced Practical Challenges & Exercises.
🎓 COURSERA PARTNER:Earn professional Google, Meta, and IBM certificates to supercharge your resume.
REFERENCEjavascript

javascript Documentation

LOADING ENGINE...

throw Statement

AI & DATA SCIENCE // throw

throw creates a custom error that propagates up the call stack until caught by a try...catch block.

Syntax

throw new Error('Something went wrong');
throw new TypeError('Expected a string');
throw { code: 404, message: 'Not found' }; // any value

Deep Dive Course

**throw** can throw any value, but by convention always throw **Error objects** (or subclasses) so catch blocks get a consistent `.message` and `.stack` trace. Custom Error classes make error handling much more specific and testable.

1Understanding throw Statement

throw can throw any value, but by convention always throw Error objects (or subclasses) so catch blocks get a consistent .message and .stack trace. Custom Error classes make error handling much more specific and testable.

💡

Always throw Error instances, never plain strings or objects. Error objects include stack traces which are invaluable for debugging.

editor.html
function divide(a, b) {
  if (typeof a !== 'number' || typeof b !== 'number') {
    throw new TypeError('Arguments must be numbers');
  }
  if (b === 0) {
    throw new RangeError('Division by zero is not allowed');
  }
  return a / b;
}

try {
  console.log(divide(10, 2));  // 5
  console.log(divide(10, 0));  // throws
} catch (e) {
  console.error(`${e.constructor.name}: ${e.message}`);
}
localhost:3000

2Practical Example

Here is a real-world application of throw Statement showing how it is used in production JavaScript code.

editor.html
// Custom Error class
class ValidationError extends Error {
  constructor(field, message) {
    super(message);
    this.name = 'ValidationError';
    this.field = field;
  }
}

function validateEmail(email) {
  if (!email.includes('@')) {
    throw new ValidationError('email', 'Invalid email format');
  }
}

try { validateEmail('notanemail'); }
catch (e) { console.log(e.name, e.field, e.message); }
localhost:3000

3Best Practices

Follow these guidelines when working with throw Statement:

1. Always throw Error instances (or subclasses)

2. Use specific error types: TypeError, RangeError, custom errors

3. Include meaningful messages with enough context to debug

⚠️

Tip: Always throw Error instances, never plain strings or objects. Error objects include stack traces which are invaluable for debugging.

editor.html
function divide(a, b) {
  if (typeof a !== 'number' || typeof b !== 'number') {
    throw new TypeError('Arguments must be numbers');
  }
  if (b === 0) {
    throw new RangeError('Division by zero is not allowed');
  }
  return a / b;
}

try {
  console.log(divide(10, 2));  // 5
  console.log(divide(10, 0));  // throws
} catch (e) {
  console.error(`${e.constructor.name}: ${e.message}`);
}
localhost:3000

Examples

Example 01Basic Usage
function divide(a, b) {
  if (typeof a !== 'number' || typeof b !== 'number') {
    throw new TypeError('Arguments must be numbers');
  }
  if (b === 0) {
    throw new RangeError('Division by zero is not allowed');
  }
  return a / b;
}

try {
  console.log(divide(10, 2));  // 5
  console.log(divide(10, 0));  // throws
} catch (e) {
  console.error(`${e.constructor.name}: ${e.message}`);
}
Example 02Advanced Example
// Custom Error class
class ValidationError extends Error {
  constructor(field, message) {
    super(message);
    this.name = 'ValidationError';
    this.field = field;
  }
}

function validateEmail(email) {
  if (!email.includes('@')) {
    throw new ValidationError('email', 'Invalid email format');
  }
}

try { validateEmail('notanemail'); }
catch (e) { console.log(e.name, e.field, e.message); }

Best Practices

  • Always throw Error instances (or subclasses)
  • Use specific error types: TypeError, RangeError, custom errors
  • Include meaningful messages with enough context to debug

Interview Question

Why should you throw Error objects instead of strings?

Hint: Stack traces and instanceOf checks.

Error objects include a stack trace (crucial for debugging), name, and message. They support instanceof checks (catch can distinguish error types). Strings lack all this context. Custom error classes extending Error allow even finer-grained error handling.

Exercises

MediumPractice using throw Statement in a real scenario.
View Solution
function divide(a, b) {
  if (typeof a !== 'number' || typeof b !== 'number') {
    throw new TypeError('Arguments must be numbers');
  }
  if (b === 0) {
    throw new RangeError('Division by zero is not allowed');
  }
  return a / b;
}

try {
  console.log(divide(10, 2));  // 5
  console.log(divide(10, 0));  // throws
} catch (e) {
  console.error(`${e.constructor.name}: ${e.message}`);
}

Frequently Asked Questions

Why should you throw Error objects instead of strings?

Error objects include a stack trace (crucial for debugging), name, and message. They support instanceof checks (catch can distinguish error types). Strings lack all this context. Custom error classes extending Error allow even finer-grained error handling.

Related Functions

trycatchError-ObjectsCustom-Exceptionsfinally