PHP ArithmeticError


引言

ArithmeticError 类继承于 Error 类。这种类型的错误可能发生在执行某些数学运算时。其中一个场景是尝试执行具有负数金额的按位移位运算。当调用 intdiv() 函数导致的值超出整数合法边界时,也会引发此错误。

ArithmeticError 示例

在以下示例中,尝试使用带负运算数的二进制移位运算符。这会导致 ArithmeticError。

示例

 在线演示

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

输出

这将产生以下结果 −

Bit shift by negative number

如果对 intdiv() 函数的调用导致无效的整数,则会引发 ArithmeticError。如下例所示,PHP 中允许的最小整数 (PHP_INT_MIN) 不能被 -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

更新于: 2020 年 9 月 21 日

199 次浏览

开启您的 职业生涯

完成课程即可获得认证

开始学习
广告
© . All rights reserved.