C# error handling (NaN)
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.
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))...
It sounds as if your parser is just returning NaN
, not throwing an exception. You can test for 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
}
You can also try turning on "Check for 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 an overflow and underflow (instead of wrapping). It may or may not apply to the ln function. Give it a try.
精彩评论