-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
  • 135,557
  • 38
  • 250
  • 339
sulayman
  • 97
  • 2
  • 6

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
  • 21,969
  • 6
  • 50
  • 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,151
  • 1
  • 31
  • 38