Choosing an Error and Its Message

Your port of parseAmount() now refuses Joan’s refund on line 6 with throw new Error(). The refund is only one bad row, though. Number("n/a") and Number("1,250.00") don’t throw an error the way float() does, so those rows slip into the total, and the trustees’ report reads £NaN.

In this lesson, you’ll pick the error type that fits a bad amount and give it a message that says what arrived, so Joan finds out about rows like those.

Look Inside a Thrown Error

In Python, an exception’s class says what kind of problem it is. Joan’s parse_amount() raises a ValueError for the refund, and a handler can read the kind and the message:

Language: Python
def parse_amount(text):
    amount = float(text)
    if amount <= 0:
        raise ValueError(f"amount must be positive, got {amount}")
    return amount

try:
    parse_amount("-40.00")
except ValueError as err:
    print(type(err).__name__)
    print(err)

Python prints ValueError, then amount must be positive, got -40.0. A JavaScript error is an instance of a class too. Here, it’s RangeError, the built-in type the next section picks for a bad amount. Like every built-in error, it carries its class’s name as a string in .name:

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);
  console.log(err.message);
}

parseAmount("-40.00");

The last call has no catch, so it also shows how an uncaught error prints:

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.