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:

// Define a function named validate_Positive_Number that takes one parameter: n
function validate_Positive_Number(n) {
  // Check if n is less than 0
  if (n < 0) {
    // If n is negative, throw an error indicating negative numbers are not allowed
    throw new Error('Error: Negative numbers are not allowed.');
  // If n is not negative, return n
  return n;

// Call the validate_Positive_Number function with argument 3 and log the result to the console
// Call the validate_Positive_Number function with argument -5, which will throw an error, and handle it


"Error: Error: Negative numbers are not allowed.

Note: Executed on JS Bin


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: 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.