Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# error handling (NaN)

Tags:

c#

I have written simple math function plotter in C# using Patrick Lundin´s Math free parser.

Now, my code snippet is this:

for (float value = -xaxis; value < xaxis; value += konst)
        {
            hash.Add("x", value.ToString());
            double result = 0;
            result = parser.Parse(func, hash);...

This works perfectly for functions defined on real numbers. But, when I want want to parse functions defined only on R+ for example, ln(x), naturally parser gives NaN into result.

Now, I tried to handle it thru exception handling, like so:

for (float value = -xaxis; value < xaxis; value += konst)
        {
            hash.Add("x", value.ToString());
            double result = 0;
            try{
            result = parser.Parse(func, hash);
            }
            catch {
            count = false;  //just a variable I am using to draw lines
            continue; // I hoped to skip the "wrong" number parsed until I came to R+ numbers
            }...

But this doesen´t work, while debugging, catch is not executed at all.

Please, what am I doing wrong? Thanks.

like image 861
B.Gen.Jack.O.Neill Avatar asked Dec 04 '22 10:12

B.Gen.Jack.O.Neill


1 Answers

You say that the parser returns NaN. That is not an exception, which is what a try/catch handles. So there is no exception for the catch block, hence it never being run.

Instead, you should test your result against NaN like so:

if(double.IsNaN(result))...
like image 112
Andrew Barber Avatar answered Dec 31 '22 07:12

Andrew Barber