LearnFrenzy
Sign in Take a free test

Error Handling · Error Handling Coding Problems · Question 3

Throw and handle typed errors for input in JavaScript Solution, output & explanation

  • Program
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 3 Back to Exercise

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.

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!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links