PHP DivisionByZeroError

PHPServer Side ProgrammingProgramming

Introduction

DivisionByZeroError class is a subclass of ArithmeticError class. This type of error occurs when division operation involves value of denominator as zero. This can also occur when a modulo operator (%) has 0 as second operator, and intdiv() function having second argument as 0.

DivisionByZeroError Example

In first example, we try to perform modulo division of 10 and 0 using % operator to induce DivisionByZeroError.

Example

 Live Demo

<?php
try {
   $a = 10;
   $b = 0;
   $result = $a%$b;
   echo $result;
}
catch (DivisionByZeroError $e) {
   echo $e->getMessage();
}
?>

Output

This will produce following result −

Modulo by zero

If call to intdiv() function with 0 as second argument also raises DivisionByZeroError as follows

Example

 Live Demo

<?php
try {
   $a = 10;
   $b = 0;
   $result = intdiv($a,$b);
   echo $result;
}
catch (DivisionByZeroError $e) {
   echo $e->getMessage();
}
?>

Output

This will produce following result −

Division by zero

Division operator (/) having 0 as denominator, however fails to raise error, instead raises warning because division results in PHP constant INF

Example

 Live Demo

<?php
try {
   $a = 10;
   $b = 0;
   $result = $a/$b;
   echo $result;
}
catch (DivisionByZeroError $e) {
   echo $e->getMessage();
}
?>

Output

This will produce following result −

PHP Warning: Division by zero in C:\xampp\php\test.php on line 5
INF
raja
Published on 21-Sep-2020 14:57:48
Advertisements