Reputation: 3
I have created this function that correctly displays the infinity symbol when trying to enter 0 into the Y text box. However I still get the division by zero error... here is my code.
here is the case for switch statment
case '/':
$prod = $x / $y;
break;
hh
//check for divide by 0
function check0($y)
{
if ($y == 0)
throw new Exception ($prod = "∞");
return FALSE;
}
try
{
check0($y);
$prod = $x /$y;
}catch(Exception $zero){
echo $zero->getMessage();
}
Upvotes: 0
Views: 5054
Reputation: 456
In my case everything works fine. Be sure, you are not trying to use division earlier in your script, because it look's like.
case '/':
$prod = $x / $y;
break;
starts before your function call.
Upvotes: 0
Reputation: 208
You must call check0() before division. You should return FALSE if y == 0, TRUE otherwise. If return TRUE then do division. However it's not necessary call a method to do this!
Upvotes: 0
Reputation: 22372
Your logic feels ... mmm well entangled.... Here have a look at this:
<?php
function divide($x, $y) {
if ( $y === 0 )
throw new Exception("Divide By Zero");
return $x/$y;
}
try {
$product = divide(3, 0);
}
catch(Exception $e) {
if ( $e->getMessage() == "Divide By Zero" )
$product = "∞";
else
$product = NULL;
}
print "Product is $product\n";
?>
Upvotes: 0
Reputation: 9929
First: you are doing a division at the second line code (which can be devision by zero).
Second: no need to return false in your method since you are throwing an error.
Third: Why using an exception here and not just let you method return true of false and check on that before executing the devision.
Fourth: Why having a method if you only need to check on the value of $y. Calling the method or including an if-statement requires both just one line of code.
So, why can't it just be like:
case '/':
if($y > 0)
$prod = $x / $y;
break;
Upvotes: 2
Reputation: 191749
This is because you actually do the division near the top (in the case
).
Upvotes: 0