Marc Howard
Marc Howard

Reputation: 3

Division by zero, php

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 = "&#8734");

    return FALSE;
 }

 try
 {
    check0($y);
    $prod = $x /$y;   
 }catch(Exception $zero){
     echo $zero->getMessage();
 }

Upvotes: 0

Views: 5054

Answers (5)

fperet
fperet

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

Matteo Vinci
Matteo Vinci

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

Ahmed Masud
Ahmed Masud

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 = "&#8734";
        else
            $product = NULL;
    }
    print "Product is $product\n";

?>

Upvotes: 0

Bas Slagter
Bas Slagter

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

Explosion Pills
Explosion Pills

Reputation: 191749

This is because you actually do the division near the top (in the case).

Upvotes: 0

Related Questions