Throwing your own errors
Sometimes you want to trigger an error because you have detected an invalid
situation. For that you use throw:
function squareRoot(n) {
if (n < 0) {
throw new Error("Cannot take the square root of a negative number");
}
return Math.sqrt(n);
}
When throw runs, the function is interrupted immediately and control rises
looking for a catch to handle it.
Throw Error objects, not strings
Although throw "text" is valid, always throw an Error object (or a
subclass). Error objects carry a message, a name and a stack trace
(stack) that help with debugging:
throw new Error("Descriptive message");
Validating inputs: a good habit
Throwing errors early when arguments are not valid makes your code more predictable. It is better to fail fast with a clear message than to silently produce an incorrect result.
Examples
Validate arguments by throwing an error
function divide(a, b) {
if (b === 0) {
throw new Error("Cannot divide by zero");
}
return a / b;
}
try {
console.log(divide(10, 2));
console.log(divide(10, 0));
} catch (e) {
console.log("Caught:", e.message);
}