Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
PHP ArithmeticError
The ArithmeticError class is inherited from the Error class. This type of error occurs while performing certain mathematical operations. One such scenario is attempting to perform a bitwise shift operation by a negative amount. This error is also thrown when a call to the intdiv() function results in a value that is beyond the legitimate boundaries of an integer.
Bitwise Shift with Negative Number
In the following example, an attempt is made to use the binary shift operator with a negative operand. This results in an ArithmeticError ?
<?php
try {
$a = 10;
$b = -3;
$result = $a << $b;
}
catch (ArithmeticError $e) {
echo $e->getMessage();
}
?>
Bit shift by negative number
Integer Division Overflow
If a call to the intdiv() function results in an invalid integer, ArithmeticError is thrown. As shown in the example below, the minimum allowed integer in PHP (PHP_INT_MIN) cannot be divided by -1 ?
<?php
try {
$a = PHP_INT_MIN;
$b = -1;
$result = intdiv($a, $b);
echo $result;
}
catch (ArithmeticError $e) {
echo $e->getMessage();
}
?>
Division of PHP_INT_MIN by -1 is not an integer
Common Scenarios
ArithmeticError typically occurs in these situations:
- Bitwise left or right shift by negative numbers
- Integer division overflow with
intdiv() - Operations that exceed integer boundaries
Conclusion
ArithmeticError helps catch mathematical operations that would produce invalid results. Always use try-catch blocks when performing operations that might exceed integer limits or involve negative shift operations.
