Skip to content
Tutorials Center
My learning

Topics

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.

PHP
try {
    echo 10 % 0;
} catch (DivisionByZeroError $e) {
    echo $e->getMessage();
}

Try it

PHP Which operations throw

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.

PHP ArithmeticError from intdiv() and shifts

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

PHP
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 returned INF or NAN. Since PHP 8.0 it throws DivisionByZeroError, like % and intdiv() always did.
  • fdiv() never throws. It follows IEEE 754 and returns INF, -INF or NAN. Use it when you want a float result and prefer to test with is_nan() or is_infinite().
  • fmod() does not throw either. A zero divisor gives NAN.
  • % works on integers. Operands are converted to integers first, so 5.9 % 0 still throws.
  • Prefer a guard to a catch. Checking $divisor === 0 or $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 Error or Throwable, not Exception. catch (Exception $e) lets this error fly past.
  • Float overflow is not an error. Large float results become INF silently, and integer overflow in +, - and * turns the result into a float.