Treat division by zero

2

I have the following function in PHP:

public function teste() {
    $conta = "0/(0+0+0)";
    eval('$result = (' . $conta . ');');
    echo $result;
}
In this case, the formula (in the example 0 / (0 + 0 + 0) obviously returns error because of division by zero.) The problem is that this formula is built dynamically and can occur from division by zero. I would like it to return only zero and not the error.

    
asked by anonymous 21.02.2018 / 13:45

2 answers

7

First, you should not use eval() . You have to have a very strong programming domain to use it without problems. And whoever has this domain always finds a better solution.

Division by zero is considered a programming error , it's A simple if resolves . But in this case neither need since you know that it is 0, you do not have to do this in real code.

Always treating division by 0 as resulting in 0 is a mathematical error, if this were correct the mathematics would do this. And when it makes sense for some other reason than the mathematician is using the number for a function he should not have. Again, programming errors should not be treated as if they were normal, or as exceptions.

When capturing exception, and in good code this rarely occurs, never capture Exception , this exception it should even be abstract. Perhaps everything that serves to inherit should.

See also:

21.02.2018 / 15:29
2

Putting a try / catch would not be the solution?

public function teste() {
    $conta = "0/(0+0+0)";
    try {
      eval('$result = (' . $conta . ');');
      echo $result;
    }
    catch(Exception $e) {
      echo 0;
    }    
}
    
21.02.2018 / 13:50