C# NotFiniteNumberException Doesn't work
I want my program to throw an exception when some floating point variable reaches infinity or is Nan NotFiniteNumberException which 开发者_JAVA百科looks like a solution but there is a problem. This
try
{
Single x = 5;
x = x / 0;
x = x + 1;
}
catch (NotFiniteNumberException ex)
{
//bla bla bla
}
won't throw anything.
I'm aware of IsNan
and IsInfinity
methods but that's not what I'm looking for.
That's because your division won't throw a NotFiniteNumberException
. It will simply return infinity for x
.
From the documentation of NotFiniteNumberException:
NotFiniteNumberException is available for programming languages that do not support the concepts of infinity and Not-a-Number in floating-point operations.
C# does support infinity and Not-a-Number for floating-point operations, so this exception does not apply here. You need to manually check the value of x
after performing the division.
The NotFiniteNumberException is only there as support for languages which do not natively support infinity. C# will never throw this exception. See here for one example.
As a side note, if you want to get an exception for reaching inf or nan, see my answer with code example here: How do I force the C# compiler to throw an exception when any math operation produces 'NaN'?
There, only exceptions for NaN are set, but feel free to look into Visual Studio's version of float.h for other flags, and here: http://www.fortran-2000.com/ArnaudRecipes/CompilerTricks.html#x86_FP for an example on how to set them.
You will not get a NotFiniteNumberException-exception, though, but rather a System.ArithmeticException (tested on VS 2012).
Ehhh,
x = x / 0;
will cause a "DivisionByZeroException", so you're not gonna catch much here.
精彩评论