First, the code you posted works the same on both PHP 5 and PHP 7. It didn't use to throw an exception on PHP 5; this functionality (throw exceptions instead of triggering runtime errors and warnings) was introduced in PHP 7.
You could in PHP 5 (and you still can in PHP 7) install an error handler that converts the errors to exceptions and throws them. There already are several links (in other answers and comments) to answers where this technique is displayed.
The documentation of the new class DivisionByZeroError
(introduced in PHP 7) explains:
DivisionByZeroError
is thrown when an attempt is made to divide a number by zero.
Unfortunately, it seems the exception is thrown only on $x % 0
and intdiv($x, 0)
. The division by zero using the regular division operator $x / 0
doesn't throw the exception, it still works the same way it worked on PHP 5 (i.e. triggers a warning).
There is a bug #71306 reported for this situation on the PHP support site but it was officially classified as "not a bug" because the division operator /
produces a floating point number and the floating point representation provides support for ±INF
or NaN
.
In conclusion, in PHP 7, the division by zero using /
triggers a warning and returns INF
or -INF
. Only the modulo operator (%
) and the integer division (function intdiv()
) throw DivisionByZeroError
when the divider is zero.