I am facing an odd problem in C#, where I need to evaluate some mathematical string expressions, which may divide by 0
. Here is an example:
string expression = GetUserInput(); // Example: "(x + y) / z", where z may equal to 0
I am currently using NCalc library for evaluating this expression, which throws a DivideByZeroException
if the z
argument in current expression is 0
.
I tried catching the exception by doing:
try {
string formula = GetUserInput();
Expression exp = new Expression(formula);
// ...
exp.Evaluate(); // Throws a DivideByZeroException
} catch (DivideByZeroException e) {
//ignored
}
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.
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.
Is there a way to evaluate a mathematical expression in C# in a "safe" way, where attempting to divide by 0
will return a static number (0
, or infinity), without throwing an exception?