-5

I am doing this:

try
{
    $result=100/0;
}
catch(Exception $e)
{
    $result=0;
}

I am getting Division by Zero exception:

Warning: Division by zero

but I want to make the result zero when exception occurs. How can I do it. Thanks,

Álvaro González
  • 142,137
  • 41
  • 261
  • 360
sulayman
  • 137
  • 2
  • 7

2 Answers2

3

Rather than catching the exception (although as noted by tlenss you are getting a warning) and ignoring it (since you might miss other important exceptions consider checking the division first. I.e.

$divisor = 0;
$num = 100;
if($divisor){
    $result=100/0;
}else{
    $result = 0;
}
Jim
  • 22,354
  • 6
  • 52
  • 80
1

You can use ErrorException to throw the PHP warnings/errors as exceptions:

function exception_error_handler($errno, $errstr, $errfile, $errline ) {
    if ( 'Division by zero' == $errstr) {
        throw new ErrorException($errstr, 0, $errno, $errfile, $errline);
    }
}
set_error_handler("exception_error_handler");

try
{
    $result=100/0;
}
catch(Exception $e)
{
    $result=0;
}

echo $result;
bitWorking
  • 12,485
  • 1
  • 32
  • 38