PHP Exceptions

Code Snippets Exceptions


In this code snippet, we’ll learn how to throw and handle an exception in PHP.

Exceptions are used to indicate that an error has occurred within our code.

For this demo, we’ll make a simple function that returns the sum of all the elements in a given array. But if the array is empty we’ll throw an exception. We’ll also check the data type of each element using gettype() to make sure the provided value is in fact a number, else an exception will be thrown.

Finally, the try catch block will be used to gracefully handle any exceptions.  

Let’s see the code example below.



//Entry point////////////////////////////////////////////////

$array = [ 11, 56, 5, 8 ]; //Returns sum: 80
//$array = []; //Throws exception: Array is Empty!
//$array = [ "5", 58, 9, 23 ]; //Throws exception: A non numeric value was encountered!

    //Any exceptions that come up from the code executed form within this code block will be caught by the catch block below.
    echo sumArray($array);
}catch(Exception $ex){
    echo "En error occured: " . $ex->getMessage();
    //The code in this block will always run(exception or not).
    //It can be used for cleanup(logging, closing connections, etc).



function sumArray($array){
    //Make sure the array isn't empty.
    if(count($array) <= 0)
        throw new Exception("Array is Empty!");

    $sum = 0;
    foreach($array as $element){
	//Use the gettype() function to check if for the correct data type.
        if(gettype($element) != "integer" && gettype($element) != "double")
            throw new Exception("A non numeric value was encountered!"); 

        $sum += $element;

    return $sum;


Leave a Reply

Your email address will not be published. Required fields are marked *

The following GDPR rules must be read and accepted:
This form collects your name, email and content so that we can keep track of the comments placed on the website. For more info check our privacy policy where you will get more info on where, how and why we store your data.

Advertisment ad adsense adlogger