Make a division that reports a problem by throwing an error.
What to build
A function divide(a, b) that refuses bad input, and a loop that deals with that refusal and carries on.
Requirements
divide(a, b)returnsa / b.- If
bis 0, it throws an Error with the messagecannot divide by zero. - For each input line, print the result, or print
error:followed by the message.
Input
Several lines, each two numbers separated by a space.
Output
One line per input line.
Constraints
There are from 1 to 50 lines, and the numbers are whole numbers from -1000 to 1000.
Example
Input:
10 2
1 0
Output:
5
error: cannot divide by zero
Why it works
In JavaScript, 1 / 0 is Infinity, with no error, so the function has to check for itself. Catching inside the loop lets one bad line fail without stopping the others.
Examples
Example 1 · Input
10 2
Expected output
5
Example 2 · Input
1 0
Expected output
error: cannot divide by zero
Hints
Hint 1
In divide, throw new Error("cannot divide by zero") when b is 0.
Hint 2
Wrap the call in try ... catch.
Hint 3
err.message is the text you passed to Error.
Solution
Show one correct solution (try it yourself first)
function divide(a, b) {
if (b === 0) {
throw new Error("cannot divide by zero");
}
return a / b;
}
let line = prompt();
while (line !== null) {
const [a, b] = line.split(" ").map(Number);
try {
console.log(divide(a, b));
} catch (err) {
console.log(`error: ${err.message}`);
}
line = prompt();
}