Throw an error when input is bad, catch it further up, and run cleanup code in finally either way.
JavaScript · beginner · 7 min · 13 steps · free
function parseAge(text) {
const age = Number(text);
if (Number.isNaN(age)) {
throw new Error(`"${text}" is not a number`);
}
return age;
}
try {
console.log(parseAge('36'));
console.log(parseAge('abc'));
console.log('never printed');
} catch (err) {
console.log('Error:', err.message);
} finally {
console.log('done checking');
}parseAge already exists. This is called hoisting.parseAge(), with text = "36". It gets its own variables.age is created with the value 36.Number.isNaN(age) is false, so the if-block is skipped.parseAge returns 36.parseAge() has finished, so its variables are gone. It prints 36.parseAge(), with text = "abc". It gets its own variables.age is created with the value NaN.throw stops parseAge at once and sends the error up the call stack.Error: "abc" is not a number.finally runs whether or not there was an error: a good place for cleanup.Answer: Stops the program
Answer: Yes
← async and await · Changing the Page (the DOM) →