w3resource

PHP Function: Handling empty string exception


6. Empty String Exception

Write a PHP function that takes a string as input and throws an exception if the string is empty.

Sample Solution:

PHP Code :

<?php
function validateString($inputString) {
    if (empty($inputString)) {
        throw new Exception("String should not be empty!");
    }
}

try {
    $string = "";
    validateString($string);
    echo "Valid string: " . $string;
} catch (Exception $e) {
    echo "An error occurred: " . $e->getMessage();
}
?>

Sample Output:

An error occurred: String should not be empty

Explanation:

In the above exercise, we have a function validateString() that takes a string $inputString as input. Inside the function, we use the empty() function to check if the string is empty. If it is, we throw a new instance of the Exception class with the message "String should not be empty!"

In the main code, we call the validateString() function with an empty string. Since the string is empty, it throws an exception. The exception is caught in the catch block, and the error message is displayed using $e->getMessage ().

Flowchart:

Flowchart: Handling empty string exception

For more Practice: Solve these Related Problems:

  • Write a PHP function that accepts a string input and throws an exception if the string is empty, then catches and handles the exception.
  • Write a PHP script to validate user input for a non-empty string and throw an exception on failure, outputting a custom message.
  • Write a PHP program that simulates form input processing by checking for an empty string and throwing an exception accordingly.
  • Write a PHP script to use a try-catch block that enforces non-empty string validation and prompts for re-entry if an exception is thrown.

PHP Code Editor:



Contribute your code and comments through Disqus.

Previous: Custom exception for missing file.
Next: Multiple catch blocks.

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.