w3resource

JavaScript Function: Custom Error on the second number zero

JavaScript Error Handling: Exercise-3 with Solution

Write a JavaScript function that accepts two numbers as parameters and throws a custom 'Error' if the second number is zero.

Sample Solution:

JavaScript Code:

function divide_Numbers(n1, n2) {
  if (n2 === 0) {
    throw new Error('Error: Division by zero is not allowed.');
  }  
  return n1 / n2;
}
console.log(divide_Numbers(8, 3));
console.log(divide_Numbers(8, 0));

Sample Output:

2.6666666666666665
"error"
"Error: Error: Division by zero is not allowed.

Note: Executed on JS Bin

Explanation:

In the above function "divide_Numbers()", we first check if n2 is equal to zero. If it is, we throw a custom Error with the message 'Error: Division by zero is not allowed.' This prevents the function from performing a division by zero operation, which would result in an error.

If n2 is not zero, the function continues and calculates the division of n1 by n2 using the division operator (/). The result is then returned.

Flowchart:

Flowchart: Validate integer parameters with custom Error.

Live Demo:

See the Pen javascript-error-handling-exercise-3 by w3resource (@w3resource) on CodePen.


Improve this sample solution and post your code through Disqus

Error Handling Exercises Previous: Handling TypeError with Try-Catch block.
Error Handling Exercises Next: Custom Error on a negative number.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.