JavaScript Function: Validate integer parameters with custom Error
JavaScript Error Handling: Exercise-1 with Solution
Throw Error for Non-Integer
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:
Output:
"Number is valid:" 12 "Error:" "Invalid number. Please input an integer."
Note: Executed on JS Bin
Explanation:
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:
Live Demo:
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.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics