Throwing Errors

Sometimes errors are thrown implicitly by the JavaScript runtime (like trying to access properties of undefined). However, you will often need to trigger errors yourself when your application’s logic encounters an invalid state.

You do this using the throw keyword.

The throw Statement

When you throw an error, execution of the current function stops immediately, and control is passed to the nearest catch block (or crashes the program if none exists).

function validateAge(age) {
  if (age < 0) {
    // Intentionally trigger an error
    throw new Error("Age cannot be negative");
  }
  return true;
}

What Can Be Thrown?

JavaScript allows you to throw absolutely anything, not just Error objects.

// Technically valid, but highly discouraged
throw "Something went wrong";
throw 404;

For consistency, predictability, and maintainability, it is a strict best practice to always throw an Error object, as it inherently captures a stack trace to help you debug where the failure originated.

Practical Example

A common scenario for throwing errors is validating input constraints before processing data.

function sendSMS(msg) {
  // Validate the strict 70-character limit
  if (msg.length > 70) {
    throw new Error("Message exceeds the 70 character limit.");
  }
  
  // This code only runs if no error was thrown
  return `Message sent: ${msg}`;
}