PHP ArithmeticError


Introduction

ArithmeticError class is inherited from Error class. This type of error may occurwhile performing certain mathemetical operations. One such scenario is attempt to perform bitwise shift operation by negative amount. This error is also thrown when call to intdiv() function results in value such that it is beyond legitimate boundaries of integer.

ArithmeticError Example

In Following example, an attempt is made to use binary shift operator with negative operand. This results in ArithmeticError.

Example

 Live Demo

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

Output

This will produce following result −

Bit shift by negative number

If call to intdiv() function results in invalid integer, ArithmeticError is thrown. As shown in the example below, the minimum allowed integer in PHP (PHP_INT_MIN) can not be divided by -1

Example

 Live Demo

<?php
try {
   $a = PHP_INT_MIN;
   $b = -1;
   $result = intdiv($a, $b);
   echo $result;
}
catch (ArithmeticError $e) {
   echo $e->getMessage();
}
?>

Output

This will produce following result −

Division of PHP_INT_MIN by -1 is not an integer

Updated on: 21-Sep-2020

143 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements