w3resource

JavaScript Function: Custom Error on an empty array

JavaScript Error Handling: Exercise-5 with Solution

Write a JavaScript function that takes an array as a parameter and throws a custom 'Error' if the array is empty.

Sample Solution:

JavaScript Code:

function validateArrayNotEmpty(arr) {
  if (arr.length === 0) {
    throw new Error('Array is empty!');
  }
}

// Example usage:
try {
  const nums1 = [1, 2, 3, 4];
  validateArrayNotEmpty(nums1); // Valid non-empty array

  const nums2 = [];
  validateArrayNotEmpty(nums2); // Throws an error
} catch (error) {
  console.log('Error:', error.message);
}

Sample Output:

"Error:"
"Array is empty!"

Note: Executed on JS Bin

Explanation:

In the above example -

The "validateArrayNotEmpty()" function checks the array length using the length property. If the length is 0, we throw an 'Error' with the custom message 'Array is empty!'.

In the example usage, we call the "validateArrayNotEmpty()" function twice. The first call with nums1 containing [1, 2, 3, 4] is a valid non-empty array, so no error is thrown. The second call with nums2 containing an empty array [] throws an error, which is caught by the catch block. In the catch block, we log the custom error message using error.message.

Flowchart:

Flowchart: Custom Error on an empty array.

Live Demo:

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


Improve this sample solution and post your code through Disqus

Error Handling Exercises Previous: Custom Error on a negative number.
Error Handling Exercises Next: Custom Error on an empty string.

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.