0

If I get a division by zero, how can I catch it and just echo an error or something of that nature?

Here's the line of code in question:

$percent = round(100.0*($row['p2']/$row['p1']-1));
Alex
  • 161
  • 5
  • 19

3 Answers3

1

Just check that $row['p1'] is not zero.

If it is zero do something else (e.g. report an error)

Ed Heal
  • 57,599
  • 16
  • 82
  • 120
-1

Division by zero in PHP returns false and displays a warning message. You can squelch the warning message by appending @ to the expression in question.

$foo = @(10 / 0);

if ($foo === false) {
   // Division by zero
}

It would be cleaner to just try to avoid dividing by zero in the first place though.

Suppressing warning messages is usually a sign that you should be doing something differently. For instance, simply check if the integer is 0 before using it for division.

Hubro
  • 52,462
  • 63
  • 210
  • 362
-2

If value of $row['p1'] is 0, then you will get division by zero error. If you want to catch it without showing ugly Exception in the UI, you can write like this.

try {
    $percent = round(100.0*($row['p2']/$row['p1']-1));
} catch() {
    echo 'Caught exception: ',  $e->getMessage(), "\n";
}

You will get the exact error message now. And better to use the condition if(0 !== $row['p1']).

prava
  • 3,698
  • 2
  • 21
  • 34