Module 26: Debugging and Testing
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
- Throw an error when something is wrong and the function can't sensibly continue:
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;
}
- Catch it where you can do something useful: show a message, try another way, or log it.
- An error has a
message(what went wrong) and astack(where it happened). -
Fail early and loudly. A function that silently returns
0orNaNfor bad input hides the problem until it shows up somewhere confusing, like a bill for ₹NaN. -
Don't catch errors just to hide them. An empty
catch {}is almost always a bug. - You can make your own error types for clarity:
class ValidationError extends Error {}(classes are covered in Module 29).
🖱️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.
