PHP program to demonstrate the Divide By Zero Exception using exception handling

Here, we are going to demonstrate the Divide By Zero Exception using exception handling in PHP. By Nidhi Last updated : December 19, 2023

Prerequisites

To understand this example, you should have the basic knowledge of the following PHP topics:

Handing Divide By Zero Exception

Here, we will use try, catch, and throw keywords to demonstrate the DivideByZero exception in a PHP program.

PHP code to handle Divide By Zero Exception

The source code to demonstrate the Divide By Zero Exception using exception handling is given below. The given program is compiled and executed successfully.

<?php
//PHP program to demonstrate the 
//Divide By Zero Exception using exception handling.
try
{
    $A = 10;
    $B = 0;

    if ($B == 0) throw new Exception("Divide by Zero exception occurred");
    $C = $A / $B;
    printf("Value of C: %d<br>", $C);
}
catch(Exception $e)
{
    printf("Exception: %s", $e->getMessage());
}
?>

Output

Exception: Divide by Zero exception occurred

Explanation

Here, we created used try and catch block. In the try block, we created two local variables $A, $B that are initialized with 10 and 0 respectively.

if($B==0)
    throw new Exception("Divide by Zero exception occurred");

Here we check the condition, if the value of $B is 0 then it will throw an exception 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.