The throw Statement
You'll learn how to manually signal errors in your code using JavaScript's throw keyword.
What Is Throwing an Exception?
So far you've caught errors with try/catch, but sometimes you need to create errors intentionally. The throw statement lets you manually generate an exception—stopping normal execution and jumping to the nearest catch block (or crashing if none exists).
Think of throw like pulling an emergency brake: you're deliberately halting the current process because something's wrong that shouldn't continue.
Basic Throw Syntax
You can throw any value, but typically you throw an Error object:
function divide(a, b) {
if (b === 0) {
throw new Error("Cannot divide by zero");
}
return a / b;
}
try {
console.log(divide(10, 2)); // 5
console.log(divide(10, 0)); // throws error
console.log("This won't run");
} catch (error) {
console.log("Caught:", error.message); // "Caught: Cannot divide by zero"
}
When to Use Throw
Use throw when:
- Input validation fails: a function receives invalid arguments
- Preconditions aren't met: required data is missing or malformed
- Impossible states occur: something that "should never happen" does
function getUser(id) {
if (typeof id !== 'number') {
throw new Error("User ID must be a number");
}
// fetch and return user...
}
Throwing Custom Values
While you can throw strings or numbers, always prefer Error objects—they include stack traces for debugging:
throw "Bad input"; // Works but discouraged
throw new Error("Bad input"); // Recommended
Key Takeaway: The throw statement lets you manually create exceptions when your code detects error conditions, allowing you to signal problems clearly rather than returning misleading values.