Write parseAge(input) that throws TypeError for non-numeric input and RangeError for ages outside 0–120, and a caller that reacts differently to each type.
Solution
main.js
function parseAge(input) {
const text = String(input).trim();
if (!/^\d+$/.test(text)) throw new TypeError(`"${input}" is not a whole number`);
const age = Number(text);
if (age > 120) throw new RangeError(`${age} is not a realistic age`);
return age;
}
for (const input of ["21", " 7 ", "twenty", "-4", "150"]) {
try {
console.log(`age = ${parseAge(input)}`);
} catch (e) {
if (e instanceof TypeError) console.log(`Type problem → ${e.message}`);
else if (e instanceof RangeError) console.log(`Range problem → ${e.message}`);
else throw e;
}
}
Output Verified by running it on Node.js
age = 21
age = 7
Type problem → "twenty" is not a whole number
Type problem → "-4" is not a whole number
Range problem → 150 is not a realistic age
Built-in error types communicate what went wrong; the caller branches on instanceof and re-throws anything unexpected. "-4" fails the digits-only check, so it is a TypeError here.
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!
We use Google Analytics cookies to see how LearnFrenzy is used and make it better, and Google AdSense to keep it free.
No analytics or ad cookies are set until you accept. Privacy Policy
·
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!