• Post category:PHP

How to Handle Exception using Try Catch in PHP with Example

Try Catch PHP Example

In this article, we will see Exception handling using try and catch block with example. The code which is capable of generating an exception or error is enclosed within the try block if no exception occurs the code is executed normally while in case of exception, the code execution exits the try block and enters the catch block. Let’s see the example of try catch in PHP

Syntax:

try{
//code goes here that could lead to an exception
}
catch(Exception $e){
//exception handling code goes here
}

Example:

<?php
//trigger exception in a "try" block
try{
$numerator = 75;
$denominator = 0;
if($denominator == 0)
throw new Exception("Divide By Zero Ocuured", -233);
{
divide($numerator, $denominator);
}
}
// catch exception
catch(Exception $e)
{
echo "Message:" . $e->getMessage();
echo "<br>";
echo "getCode() : " / $e->getCode();
echo "<br>";
echo $e->__toString();

}
echo '<br>Statement following try catch Block!';
?>

Output:

try catch php example

Steps:

  1. In the above example code,  we have created two variable called $numerator and $denominator within the try block. Then initilized the value 75 to $numerator and 0 to $denominator.
  2. Then check the condition $denominator is equal to 0 using If statement. If condition is true, it divides $numerator  to $denominator.
  3. And then we create catch block and then we created Exeception name as $e. Inside catch block, we getcode and getMessage exeception.
  4. See the above outpu, if we can’t divides 75 to 0. Try block fails, so it displays the exeception error from catch block.

I hope you have understood a little about PHP Try block and Catch block execeptional handling in this article. If you have any doubts about this then please comment it below.

Leave a Reply