php的取余运算在除数为零时会抛出 floatingpointexception,必须使用 try...catch 块捕获该异常。只需将包含 % 运算符的代码包裹在 try 中,并在 catch 中指定 floatingpointexception 类型即可安全处理。

FloatingPointException 的具体触发条件是什么
当取余运算的右操作数(除数)为零时,PHP 会抛出此异常。这适用于整数和浮点数,但通常与浮点数的精度问题或显式的零值有关。

<?php
$numerator = 10;
$denominator = 0;
try {
$result = $numerator % $denominator;
echo "Result: $result";
} catch (FloatingPointException $e) {
echo "Error: Division by zero in modulo operation.";
}
?>
预期输出:Error: Division by zero in modulo operation.
立即学习“PHP免费学习笔记(深入)”;
如何区分整数和浮点数的取余异常
在 PHP 8.0+ 中,整数除以零会抛出 ArithmeticError,而浮点数除以零会抛出 FloatingPointException。取余运算同样遵循此规则:整数取余零抛出 ArithmeticError,浮点数取余零抛出 FloatingPointException。

<?php
// 整数取余零
try {
$intResult = 10 % 0;
} catch (ArithmeticError $e) {
echo "Integer ArithmeticError caught.";
}
// 浮点数取余零
try {
$floatResult = 10.5 % 0.0;
} catch (FloatingPointException $e) {
echo "Float FloatingPointException caught.";
}
?>
预期输出:Integer ArithmeticError caught. Float FloatingPointException caught.
如果同时存在整数和浮点数取余,如何统一捕获?
可以使用多 catch 块分别捕获 ArithmeticError 和 FloatingPointException,或者捕获它们的共同父类 Error。推荐分别捕获以提供更精确的错误信息。
<?php
$numerator = 10;
$denominator = 0;
try {
// 根据变量类型动态决定是整数还是浮点数
$result = $numerator % $denominator;
} catch (ArithmeticError $e) {
echo "Caught ArithmeticError for integer modulo.";
} catch (FloatingPointException $e) {
echo "Caught FloatingPointException for float modulo.";
} catch (Error $e) {
echo "Caught generic Error.";
}
?>
预期输出:Caught ArithmeticError for integer modulo.(如果 $numerator 是整数)



















