First, you shouldn’t wear eval()
. You have to have a very strong domain in programming to use it smoothly. And whoever has this domain always finds a better solution.
Division by zero is considered a programming error, is the same thing as giving a pointer error (PHP does not give it, I think, but it treats in a way that I consider harmful), it should never occur, the solution is to ensure that there is no division by zero, so you must ensure that the divisor is not zero before using it. A simple if
before it resolves. But in this case it doesn’t even need to be since you know it’s 0, you don’t have to do it in real code.
Always treating the 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 shouldn’t have. Again, programming errors should not be treated as if they were normal, or as if they were exceptions.
When catching exception, and in good codes this rarely occurs, never capture Exception
, this exception should even be abstract. Maybe everything that serves to inherit should.
See also:
If this data is dynamical Voce can do a check on them to see if they are equal to zero or not, before doing this calculation.
– Alex
could use example: a/b+c+d, would be more readable....
if (b+c+d = 0) echo '0' else ....calcula...
!?– Rovann Linhalis
The big problem is that the formula may have division or not. The user can assemble several mathematical formulas.
– Felipe Saraiva
Do you validate the validity of the formula? Or do you simply accept any string passed and leave it to give arithmetic problems in the last instance? For example, this formula would be invalid
(1 + 2 + 3*(123)
, for parenthesis is lacking.– Jefferson Quesado
I validated the expression before. But the values I have no way of knowing.
– Felipe Saraiva
@Felipesaraiva if you validate you are already compiling (the constants I put just for example). If you are compiling, you can assemble the expression tree and treat it internally, according to the order of precedence.
– Jefferson Quesado
@Jeffersonquesado is right, I’m going to go for this idea, thank you very much! Please, how do I "approve" this suggestion?
– Felipe Saraiva
@Felipesaraiva write an official reply. I am particularly lazy/lacking time to make a formal response
– Jefferson Quesado