JavaScript Function: Validate integer parameters with custom Error

JavaScript Error Handling: Exercise-1 with Solution

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

Sample Solution:

JavaScript Code:

function validateInteger(number) 
  if (!Number.isInteger(number)) 
    throw new Error('Invalid number. Please input an integer.');
  console.log('Number is valid:', number);

// Example usage:
try {
  validateInteger(12); // Valid integer
  validateInteger(2.12); // Throws an error
} catch (error) {
  console.log('Error:', error.message);

Sample Output:

"Number is valid:"
"Invalid number. Please input an integer." 

Note: Executed on JS Bin


In the above function, the "Number.isInteger()" method is used to check if the given number is an integer. If it's not an integer, the program throws a custom "Error" with the message "Invalid number. Please input an integer." If the number is valid, the program logs a success message.

In the example usage, we demonstrate how the function works by calling it with both a valid integer (42) and an invalid number (3.14). The try-catch block catches and handles any thrown error, and the error message is logged to the console.


Flowchart: Validate integer parameters with custom Error.

Live Demo:

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

Improve this sample solution and post your code through Disqus

Error Handling Exercises Previous: JavaScript Error Handling Exercises Home.
Error Handling Exercises Next: Handling TypeError with Try-Catch block.

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.