Search code examples
javadoubledivide-by-zero

Is it a good practice to add a very small number to the divisor not to deal with division by zero exception?


I want to keep my code clean and avoid unnecessary IF branches.
Is it a good practice to add a very small number to the divisor not to deal with division by zero exception? Is the below code considered a good practise?
I know that such comparison not purely 100% accurate in this case but let's it does not matter.

double safeDivision(double dividend, double divisor)
{
    return (dividend + Double.MIN_VALUE)/(divisor + Double.MIN_VALUE);
}

Solution

  • No, it can give unwanted results. How do you deal with numbers coming off an "adjusted" division by 0?

    A working code is always better then a clean but potentially bugged code