0

I have this PHP code. Whenever y becomes zero, it shows a warning instead of catching the exception. Is there anything wrong with my code?

try
{
    return($x % $y); 
    throw new Exception("Divide error..");
}
catch(Exception $e){
    echo "Exception:".$e->getMessage();
}

I got this warning:

Warning: Division by zero in file.php

The catch block is not run. What am I doing wrong?

Eric Leschinski
  • 146,994
  • 96
  • 417
  • 335
insomiac
  • 5,648
  • 8
  • 45
  • 73
  • Why not tell us what kind of warning you get?! – ThiefMaster May 18 '11 at 06:06
  • I've fixed your indentation, you might want to check the preview box underneath the question area next time: you can see how your code will come out, and fix it up a bit for easier reading. Remember, the easier you question is to read, the more answers you might get? – Nanne May 18 '11 at 06:06
  • @ThiefMaster: i have posted the warning check it out. – insomiac May 18 '11 at 06:09
  • @ibu: thanks, i have removed the return statement. Now i am able to catch the exception but it is still showing me warning.. – insomiac May 18 '11 at 06:10

3 Answers3

7

A warning is not an exception. Warnings cannot be caught with exception handling techniques. Your own exception is never thrown since you always return before.

You can suppress warnings using the @ operator like @($x % $y), but what you should really do is make sure $y does not become 0.

I.e.:

if (!$y) {
    return 0; // or null, or do something else
} else {
    return $x % $y;
}
deceze
  • 510,633
  • 85
  • 743
  • 889
  • i have removed the return statement. Now i am able to catch the exception but it is still showing me warning.. – insomiac May 18 '11 at 06:11
  • @Aby If you remove the `return` statement, you'll **always** throw and catch the exception. Exceptions are completely useless here. And regarding the warning, read my answer again. – deceze May 18 '11 at 06:12
3

Yes, you are executing the return before the throw. Hence the throw is never executed and no exception is thrown nor caught.

user703016
  • 37,307
  • 8
  • 87
  • 112
-1

this is how it should be done

$value;

try
{
    $value = $x%$y; 
}
catch(Exception $e){
  throw new Exception("Divide error..");
  echo "Exception:".$e->getMessage();
}

return $value

But since you are getting a warning if you want to hide the error and handle it discretely You can use the @ sign

$value = @$x%$y;

now you can test the value and see if it has the value it has

Ibu
  • 42,752
  • 13
  • 76
  • 103