Throwing Your Own Errors
JavaScript is not the only one that can throw errors. Your own code can throw one too, when it gets a value that makes no sense:
function validateAge(age) {
if (age < 0 || age > 120) {
throw new Error(`impossible age: ${age}`);
}
console.log(`age ${age} accepted`);
}
try {
validateAge(34);
validateAge(-5);
validateAge(50);
} catch (err) {
console.log("rejected:", err.message);
}
Output:
age 34 accepted
rejected: impossible age: -5
new Error("...") creates an error object, and the text you give it becomes its message. throw stops the function at once. The error then moves up to the code that called the function, and on up, until a catch takes it.
Look at the output again. validateAge(50) never ran. When validateAge(-5) threw, the rest of the try block was skipped and the catch block ran.
If no catch takes the error, the program stops, and done is never printed. The report shows your own message:
const age = 200;
if (age > 120) {
throw new Error(`impossible age: ${age}`);
}
console.log("done");
Output:
/box/index.js:3
throw new Error(`impossible age: ${age}`);
^
Error: impossible age: 200
at Object.<anonymous> (/box/index.js:3:9)
Why throw an error, and not just fix the value or return a special answer like -1? Because wrong values travel. An undefined in one place becomes a NaN in another, and later a wrong total in a report. By then it is hard to find where the problem started. A throw stops the program right at the source, with a message that says what was wrong. impossible age: -5 tells you much more than bad input. This idea is called fail fast.
A function that throws on bad input is also easier to trust. When it returns normally, you know the input was good.
In the exercise, make validateAge throw an error for ages below 0 or above 120.