Skip to the content

Project: crash-proof calculator

JavaScript · Unit 9: Errors and exceptions

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. 1. Complete the code

    Complete it so dividing by 0 is an error with a clear message.

  2. 2. Write the code

    Finish divide(a, b). If a or b isn't a number, throw an error with the message "Only numbers allowed". If b is 0, throw one with "You can't divide by 0". Check that they're numbers first. If everything is fine, return a / b.

  3. 3. Write the code

    You already have divide. Write calculate(a, b), which returns a string like "8 / 2 = 4". If divide throws 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".

Do this lesson

It opens in your browser. This lesson is part of the full plan; the first unit of each course is free.

See all lessons →