PHP Tutorial

PHP Examples

PHP Practice

PHP program to demonstrate the Array index out of bound exception using exception handling

Here, we are going to demonstrate the Array index out of bound exception using exception handling in PHP.
Submitted by Nidhi, on November 22, 2020 [Last updated : March 13, 2023]

Handing Array Index Out Of Bound Exception

Here, we will use try, catch, and throw keywords to demonstrate the Array index out of bounds exception in a PHP program.

PHP code to handle array index out of bound exception

The source code to demonstrate the Array index out of bound exception using exception handling is given below. The given program is compiled and executed successfully.

<?php
//PHP program to demonstrate the Array index 
//out of bound exception using exception handling.
try
{
    $colors = array(
        "Red",
        "Green",
        "Blue"
    );
    $index = 3;

    if ($index >= count($colors)) throw new Exception("Array index out of bound");

    printf("Array element: %s<br>", $colors[$index]);

}
catch(Exception $e)
{
    printf("Exception: %s", $e->getMessage());
}
?>

Output

Exception: Array index out of bound

Explanation

Here, we created used try and catch block. In the try block - we created an array that contains the name of colors. We also created the local variable $index to access the element from the array from the specified index.

if($index>=count($colors))
    throw new Exception("Array index out of bound");

Here, we check the condition, if the value of $index is greater than or equal to the total elements of the array then we will throw an exception with a specified message using the throw keyword that will be caught by catch block and print specified message on the webpage.

PHP Exception Handling Programs »





Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.