Home » PHP » PHP Examples

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

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

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

Example:

<?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





Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.
Learn PCB Designing: PCB DESIGNING TUTORIAL







Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing » Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.