Choosing an Error and Its Message

Your parseAmount() now refuses Joan’s refund with throw new Error(), but Number("n/a") and Number("1,250.00") don’t fail the way float() does. Those rows reach the total, and the trustees’ report reads £NaN. You’ll pick the error type that fits a bad amount, write a message that says what arrived, and pass an error on from a catch.

Read What an Error Carries

Python’s handler reads type(err).__name__ and str(err). A JavaScript error is a class instance too, and it carries its type name and message as properties. Here, parseAmount() throws a RangeError:

Language: JavaScript
function parseAmount(text) {
  const amount = Number(text);
  if (amount <= 0) {
    throw new RangeError(`amount must be positive, got ${amount}`);
  }
  return amount;
}

try {
  parseAmount("-40.00");
} catch (err) {
  console.log(err.name, "-", err.message);
}

For built-in errors, .name is the type’s name as a string, and the message shows -40 where Python’s shows -40.0:

Language: Program Output
RangeError - amount must be positive, got -40

Locked learning resources

Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

Locked learning resources

The full lesson is for members only. Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

Become a Member to join the conversation.