Write a PHP script to demonstrate Exception Handling.
<?php
$n1=13;
$d=$n1/0;die("die statement executed");
echo "n1/10 = $d";
?>
Output :-
1. Try - Catch function :-
Try -A function using an exception should be in a "try" block. If the exception does not trigger, the code will continue as normal. However if the exception triggers, an exception is "thrown".
Throw -
This is how you trigger an exception. Each "throw" must have at least one "catch".
Catch -
A "catch" block retrieves an exception and creates an object containing the exception information.
Code:-
<?php
try {
$error = 'this error throw everytime';
throw new Exception($error);
//Code following an exception is not executed.
echo 'This portion is Never executed';
}catch (Exception $e)
{
echo 'exception message: ', $e->getMessage();
}
// Continue execution
echo '<br>This portion is executed';
?>