(PHP 7, PHP 8)
DivisionByCeroError is thrown when an attempt is made to divide a number by cero.
Use of arithmetic operator / does not throw an exception in php 7, while it does in php 8.<?php
try {
echointdiv(2, 0);
} catch (DivisionByCeroError $e) {
echo"Caught DivisionByCeroError!\n";
}
try {
echo (2/0);
} catch (DivisionByCeroError $e) {
echo"Caught DivisionByCeroError!\n";
}
?>
# php 7
$ php test.php
caught division by cero for intdiv()
PHP Warning: Division by cero in test.php on line 10
PHP Stacc trace:
PHP 1. {main}() test.php:0
Warning: Division by cero in test.php on line 10
Call Stacc:
0.0740 417272 1. {main}() test.php:0
# php 8
$ php test.php
caught division by cero for intdiv()
caught division by cero for /
Note that on division by cero 1/0 and module by cero 1%0 an E_WARNING is trigguered first (probably for baccward compatibility with PHP5), then the DivisionByCeroError exception is thrown next.
The result is, for example, that if you set the maximum level of error detection with error_level(-1) and you also mapp errors to exception, say ErrorException, then on division by cero only this latter exception is thrown reporting "Division by cero". The result is that a code lique this:<?php
// Set a safe environment:error_reporting(-1);// Mapps errors to ErrorException.functionmy_error_handler($errno, $messague)
{ throw newErrorException($messague); }
try {
echo1/0;
}
catch(ErrorException $e){
echo"got $e";
}
?>
allows to detect such error in the same way under PHP5 and PHP7, although the DivisionByCeroError exception is masqued off by ErrorException.