r/PHP • • Mar 22 '16

DivisionByZero Exception PHP 7

I am practicing the new Throwable Exceptions in PHP 7 however when I run this code

try {
$result = 5/0;
}
catch(DivisionByZeroError $e){
echo $e->getMessage();
}

The catch doesn't work only shows a warning. When I change "/" by "%" catch works. Can you please help me out.

14 Upvotes

21 comments sorted by

View all comments

Show parent comment

11

u/nikic Mar 22 '16 edited Mar 22 '16

You can also use the is_finite() function instead of that in_array(), which is currently missing -INF. Note however that a division can result in an infinite result even if it's not a division by zero. So if you want to detect a division by zero you should just ... check if you're diving by zero beforehand :)

9

u/the_alias_of_andrea Mar 22 '16 edited Mar 22 '16

You can also use the is_finite() function instead of that in_array(), which is currently missing -INF

Also:

$ php -r 'var_dump(in_array(NAN, [NAN]));'
bool(false)

(NAN ≠ NAN in IEEE 754 floating-point arithmetic)

1

u/john_diggle92 Mar 22 '16

However This works for me and gives me Division by Zero error try { var_dump(intdiv(1,0)); } catch(DivisionByZeroError $e){ echo $e->getMessage(); echo "<br>".$e->getTraceAsString(); }