Project: crash-proof calculator
JavaScript · Unit 9: Errors and exceptions
- Full plan
- JavaScript
- Project
- 3 exercises
In JavaScript, dividing by 0 doesn't crash: it gives Infinity. A string that isn't a number gives NaN, and one that looks like a number gets converted without a word.
The program carries on with a result that's no use. Your calculator is going to warn with throw.
console.log(10 / 0);
console.log("hi" / 2);
console.log("8" / 2);Prints
Infinity NaN 4
Exercises in this lesson
You do them in the app, which checks them on the spot and explains why.
1. Complete the code
Complete it so dividing by 0 is an error with a clear message.
2. Write the code
Finish
divide(a, b). Ifaorbisn't a number, throw an error with the message "Only numbers allowed". Ifbis 0, throw one with "You can't divide by 0". Check that they're numbers first. If everything is fine, returna / b.3. Write the code
You already have
divide. Writecalculate(a, b), which returns a string like "8 / 2 = 4". Ifdividethrows an error, catch it and return "Couldn't do it: " followed by the message, like "Couldn't do it: You can't divide by 0".
It opens in your browser. This lesson is part of the full plan; the first unit of each course is free.