Module 26: Debugging and Testing

Lesson 1 of 5 · 15–25 minutes

Throwing and catching errors

🏠The everyday picture

A bank clerk who notices a cheque is unsigned doesn't quietly process it for ₹0. They stop and hand it back with a clear reason. Code should refuse bad input just as clearly.

📘What it really is

function lineTotal(price, qty) {
  if (!Number.isInteger(qty) || qty < 1) {
    throw new Error(`Quantity must be a whole number of at least 1, got ${qty}`);
  }
  return price * qty;
}

🖱️Try it

Add checks to the functions in calc.js: prices must be whole numbers of paise, zero or more; quantities must be whole numbers of at least 1. Throw clear errors. Call them with bad values inside try/catch and print the messages.

✅Quick check

A function gets "abc" as a quantity. Should it return 0 or throw an error?

Show the answer

Throw a clear error. Returning 0 hides the mistake and causes confusing results later.

What's wrong with try { ... } catch (e) {}?

Show the answer

It swallows the error silently, so a problem happens and nobody knows.

← BackModule 26
ProLearners Assist