Search code examples
c#matherror-handlingdivide-by-zero

C# - Is it possible to make divide-by-zeros return a number, instead of throwing an exception?


I have an expression that includes divisions, for which some of the denominators are sometimes zero. However, in those cases I would like that division to result in 1, instead of throwing an exception. Is there any straightforward way about doing this, or am I forced to do some if statements and changing the inputs to the expression to get this desired effect?


Solution

  • Although I must question the motives here, if you need to do it, make a function.

    double SafeDiv(double num, double denom) {
       if(denom == 0) {
          return 1;
       }
       return num/denom;
    }