0

I have made a simple calculator using php, and i want to handle exception of division by zero, I am new at this and need help how to do this, if anyone can help:- Below is my code

<?php

$result = 0;
class calculator
{
    var $a;
    var $b;
    function checkoperation($operator)
    {
        switch ($operator) {

            case 'divide':
                return $this->a / $this->b;
                break;

            case 'multiply':
                return $this->a * $this->b;
                break;

            case 'add':
                return $this->a + $this->b;
                break;

            case 'subtract':
                return $this->a - $this->b;
                break;
        }
    }
    function getresult($a, $b, $c)
    {
        $this->a = $a;
        $this->b = $b;
        return $this->checkoperation($c);
    }
}
$cal = new calculator();
if (isset($_POST['calculate_btn'])) {
    $first_num  = $_POST['first_num_txtbox'];
    $second_num = $_POST['second_num_txtbox'];
    $operation  = $_POST['operation_slctbox'];
    $result     = $cal->getresult($first_num, $second_num, $operation);
    echo "The result is: " . $result;
}
?>
s_mart
  • 735
  • 7
  • 21
shanu
  • 76
  • 1
  • 1
  • 11

4 Answers4

0

In devide case, you must check the $this->b value before make devide operator:

case 'divide':
    return ($this->b == 0) ? 'Infinitive' : $this->a / $this->b;
    break;

I hope this will help you!

Sang Lu
  • 308
  • 3
  • 10
0

put if statement at the end. I mean :

if ($second_num==0)
{echo "<h1>ERROR:CANT BE DIVIDED</h1>"}
else
{$result = $cal->getresult($first_num, $second_num, $operation);
echo "The result is: " . $result;}
Mostafa Abedi
  • 541
  • 6
  • 19
0

This would be an option right at the post check this is just one option and it checks both numbers to not be 0.

if(isset($_POST['calculate_btn']))
{   
    if($_POST['operation_slctbox'] == "divide")
    {
        if($_POST['first_num_txtbox'] !== "0" || $_POST['second_num_txtbox'] !== "0")
        {
            //do code if either are 0 and divide is selected or return with error cannot divide by 0
        }
        else
        {
           $result = $cal->getresult($first_num, $second_num, $operation);
        }
    }
    else
    {
         $result = $cal->getresult($first_num, $second_num, $operation);
    }
    echo "The result is: " . $result;
}
0

YOU can use try catch with exception handling

       case 'divide':
             try {
                if(!$this->b){
                    throw new Exception('Division by zero .');
                }
                    return $this->a / $this->b;
            } catch (Exception $e) {
                return $e->getMessage();
            }
            break;
Mithu CN
  • 605
  • 5
  • 11