Try Catch example

This is an example of the Try and Catch blocks which was introduced in PHP5, this brings PHP into line with other programming languages such as C# and VB.net.

<?php
function division($input, $division)
{
    if ($division == 0)
 {
        throw new Exception(‘Division by zero error.’);
    }
    else return $input / $division;
}
try
{
    echo division(10,2) . “<br>”;
 echo division(10,-2) . “<br>”;
 echo division(-10,2) . “<br>”;
    echo division(7,0) . “<br>”;
}
catch (Exception $e)
{
    echo ‘Caught an exception : ‘,  $e->getMessage(), “<br>”;
}

// Continue execution
echo ‘This is at the end and will srun despite the errors above’;
?>

You should now see the following

5
-5
-5
Caught exception: Division by zero error.
This is at the end and will srun despite the errors above

LEAVE A REPLY

Please enter your comment!
Please enter your name here

*