w3resource

JavaScript Function: Custom Error on a negative number

JavaScript Error Handling: Exercise-4 with Solution

Write a JavaScript function that takes a number as a parameter and throws a custom 'Error' if the number is negative.

Sample Solution:

JavaScript Code:

function validate_Positive_Number(n) {
  if (n < 0) {
    throw new Error('Error: Negative numbers are not allowed.');
  }
  return n;
}

console.log(validate_Positive_Number(3));
console.log(validate_Positive_Number(-5));

Sample Output:

3
"error"
"Error: Error: Negative numbers are not allowed.

Note: Executed on JS Bin

Explanation:

In the above exercise,

The "validatePositiveNumber()" function checks if a number "n" is less than zero using the comparison operator <. If it is, we throw a custom Error with the message 'Error: Negative numbers are not allowed.' This ensures that the function will not proceed with further operations if a negative number is passed.

If the number is not negative, the function returns the number itself.

Flowchart:

Flowchart: Custom Error on a negative number.

Live Demo:

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


Improve this sample solution and post your code through Disqus

Error Handling Exercises Previous: Custom Error on the second number zero.
Error Handling Exercises Next: Custom Error on an empty array.

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.