PHP program to handle modulo by zero exception

Here, we are going to learn how to handle an exception modulo by zero which occurs when we divide (using the modulus operator to find remainder) a number by 0?
Submitted by IncludeHelp, on April 06, 2019 [Last updated : March 12, 2023]

Modulo By Zero Exception

"The modulo by zero error" throws when we divide a number by zero to get the remainder using modulus operator (%).

Handing Modulo By Zero Exception

It can be handled by using "try...catch" statement, with DivisionByZeroError exception.

PHP code to handle modulo by zero exception

<?php
    $a = 10;
    $b = 3;
    
    try 
    {
        //dividing $a by $b - no error 
        $result = $a%$b;
        print("result: $result \n");
        
        //assigning 0 to $b
        $b = 0;

        //now, dividing $a by $b - error occurs
        $result = $a%$b;
        print("result: $result \n");        
    }
    catch(DivisionByZeroError $err){
        print("Exception... ");
        print($err->getMessage());
    }
?>

Output

result: 1
Exception... Modulo by zero

PHP Basic Programs »





Comments and Discussions!

Load comments ↻





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