C # Error Handling (NaN)

I wrote a simple math plotter in C # using the free Patrick Lundin's Math parser.

Now my code snippet:

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

This works great for functions defined on real numbers. But, when I want to analyze functions defined only on R +, for example, ln (x), the natural parser gives NaN the result.

Now I tried to handle it using exception handling, for example:

 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 does not work, while debugging, catch is not executed at all.

Please, what am I doing wrong? Thanks.

+4
source share
3 answers

You say that parser returns NaN . This is not an exception that try/catch handles. Thus, there is no exception for the catch block, so it never starts.

Instead, you should check your result on NaN as follows:

 if(double.IsNaN(result))... 
+11
source

It sounds like your parser just returns NaN without throwing an exception. You can check NaN using the static IsNaN method :

 result = parser.Parse(func, hash); if (float.IsNaN(result)) // assuming that result is a float { // do something } else { // do something else } 
+2
source

You can also try to enable "Check arithmetic overflow / underflow". It is located in your project properties under "Build-> Advanced Build Settings"

When it is turned on, arithmetic exceptions will be thrown for overflow and underflow (instead of wrapping). It may or may not apply to the ln function. Give it a try.

+2
source

All Articles