Handling errors
Things go wrong: a user types "forty" where you expected a number, a file is missing. JavaScript reports problems with errors.
You can create your own with throw:
function withdraw(balance, amount) {
if (amount > balance) {
throw new Error("Not enough money");
}
return balance - amount;
}
When an error is thrown, the function stops immediately, and so does everything that called it... unless someone catches the error:
try {
withdraw(50, 80);
console.log("This line never runs");
} catch (error) {
console.log("Problem: " + error.message); // Problem: Not enough money
}
- Code in
tryruns normally until something throws. - Then
catchruns, with the error object.error.messageis the text you gave it. - After
catch, the program carries on.
Throw when a function cannot do its job properly. Catch where you know how to recover, for example by showing a friendly message.
Number("abc") gives NaN ("not a number"). Check for it with Number.isNaN(value).
Your task
- Write
parseAge(text). It turns the text into a number and returns it, but throws:new Error("Not a number")if the text is not a number,new Error("Age out of range")if the age is below 0 or above 130.
- Write
safeParseAge(text), which returnsparseAge(text), ornullif that throws.