PHP Reference ยท Exceptions and Errors
PHP ArithmeticError and DivisionByZeroError
Reference for PHP ArithmeticError and DivisionByZeroError: when intdiv(), % and / throw, how fdiv() differs, and how to catch and avoid these errors.
ArithmeticError is thrown when a mathematical operation cannot be carried out. Its subclass DivisionByZeroError is the one you meet in practice: PHP 8 throws it when you divide or take a remainder with a zero divisor. Both extend Error, not Exception, so a plain catch (Exception $e) does not catch them.
try { echo 10 % 0; } catch (DivisionByZeroError $e) { echo $e->getMessage(); }
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.
Syntax
class ArithmeticError extends Error {} class DivisionByZeroError extends ArithmeticError {}
| Class | Thrown when |
|---|---|
DivisionByZeroError |
The divisor of /, % or intdiv() is zero. |
ArithmeticError |
A bit shift by a negative amount, or intdiv(PHP_INT_MIN, -1), whose result does not fit an integer. |
Both classes inherit the usual methods of Throwable: getMessage(), getCode(), getLine(), getTrace() and so on.
Usage notes
- PHP 8 changed
/. In PHP 7 the division operator only raised a warning and returnedINForNAN. Since PHP 8.0 it throwsDivisionByZeroError, like%andintdiv()always did. fdiv()never throws. It follows IEEE 754 and returnsINF,-INForNAN. Use it when you want a float result and prefer to test withis_nan()oris_infinite().fmod()does not throw either. A zero divisor givesNAN.%works on integers. Operands are converted to integers first, so5.9 % 0still throws.- Prefer a guard to a catch. Checking
$divisor === 0or$values === []states the rule in the code. Catch the error only at a boundary where a bad input is possible and you can recover. - Catch
ErrororThrowable, notException.catch (Exception $e)lets this error fly past. - Float overflow is not an error. Large float results become
INFsilently, and integer overflow in+,-and*turns the result into a float.
Related
Error,Throwable,TypeError,try,catch,finally- Lessons: Exceptions, Errors