How to evaluate a string expression in C# which can divide by zero?
<p>I am facing an odd problem in C#, where I need to evaluate some mathematical string expressions, which may divide by <code>0</code>. Here is an example:</p>

<pre><code>string expression = GetUserInput(); // Example: "(x + y) / z", where z may equal to 0
</code></pre>

<p>I am currently using <a href="https://ncalc.codeplex.com/" rel="nofollow">NCalc</a> library for evaluating this expression, which throws a <code>DivideByZeroException</code> if the <code>z</code> argument in current expression is <code>0</code>.</p>

<p>I tried catching the exception by doing:</p>

<pre><code>try {
    string formula = GetUserInput();
    Expression exp = new Expression(formula);

    // ...

    exp.Evaluate(); // Throws a DivideByZeroException

} catch (DivideByZeroException e) {
    //ignored
}
</code></pre>

<p>However, I need to evaluate this expression more than 6000 times (with different variables) in a time-efficient manner, so catching an exception every time significantly slows down my application.</p>

<p>I have multiple such expressions, each of which is entered by a user. I can not know if a given expression attempts to divide by zero or not.</p>

<p>Is there a way to evaluate a mathematical expression in C# in a "safe" way, where attempting to divide by <code>0</code> will return a static number (<code>0</code>, or infinity), without throwing an exception?</p>