JavaScript Function: Custom Error on an empty string

JavaScript Error Handling: Exercise-6 with Solution

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

Sample Solution:

JavaScript Code:

function validate_String_Not_Empty(str) {
  if (str.length === 0) {
    throw new Error('Sorry, the string is empty!');

// Example:
try {
  const string1 = 'Hello, World!';
  validate_String_Not_Empty(string1); // Valid non-empty string

  const string2 = '';
  validate_String_Not_Empty(string2); // Throws an error
} catch (error) {
  console.log('Error:', error.message);

Sample Output:

"Sorry, the string is empty!"

Note: Executed on JS Bin


In the "validate_String_Not_Empty()" function, we check the string length using the length property. If the length is 0, we throw an 'Error' with the custom message 'Sorry, the string is empty!'.

Next, we call the "validate_String_Not_Empty()" function twice. The first call with string1 containing 'Hello, World!' is a valid non-empty string, so no error is thrown. The second call with string2 containing an empty string throws an error, which is caught by the catch block. In the catch block, we log the custom error message using error.message.


Flowchart: Custom Error on an empty string.

Live Demo:

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

Improve this sample solution and post your code through Disqus

Error Handling Exercises Previous: Custom Error on an empty string.
Error Handling Exercises Next: Catching and handling RangeError with Try-Catch.

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.