throw, try & catch
Give a failure a clear meaning
Lesson 18 of 20 · 11 min · Module 6: Design, validate & debug
Some functions cannot produce a meaningful result for invalid input. Throwing an error lets the caller decide how to handle that failure.
Start this lesson →Free. No installation: you write and run the code in your browser, and it is checked automatically.
By the end, you’ll be able to…
- Use a consistent failure contract
- Handle type and range errors separately
The idea
Create an appropriate error and throw it. A surrounding try/catch can recover. Catch only at a point where you can make a useful decision.
try {
throw new RangeError("Score is outside 0–100");
} catch (error) {
console.log(error.message);
}
01Describe the happy path
A valid value should pass through unchanged. Inclusive boundaries mean zero and one hundred are acceptable, rather than exceptional cases.
02Choose the error by the failed rule
A numeric-looking string violates the input type contract. The finite number 101 has the right type but violates the range contract.
03Let callers recover deliberately
A UI might catch the error and show a useful message. A calculation function should not silently replace a bad score with zero, because that disguises failure as data.
Your turn
requireScore(value). Return a finite number between 0 and 100 inclusive. Throw a TypeError for anything that is not a finite number, and a RangeError for a finite number outside that interval.What the checks look for
- Accepts both inclusive boundaries
- Throws TypeError for nonnumeric or nonfinite values
- Throws RangeError outside the interval
Take this with you
A useful error explains which promise the input broke.
Go a little further
Write a caller that catches the error and returns {ok:false, message} for display.