Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
135 views
in Technique[技术] by (71.8m points)

c# - Why does this method return double.PositiveInfinity not DivideByZeroException?

I ran the following snippet in the VS2015 C# interactive and got some very weird behavior.

> double divide(double a, double b)
. {
.     try
.     {
.         return a / b;
.     }
.     catch (DivideByZeroException exception)
.     {
.         throw new ArgumentException("Argument b must be non zero.", exception);
.     }
. }    
> divide(3,0)
Infinity    
> 3 / 0
(1,1): error CS0020: Division by constant zero
> var b = 0;
> 3 / b
Attempted to divide by zero.
> 

Why did the method return infinity while 3 / 0 threw an error and 3 / b threw a formated error? Can I force the division to have thrown an error instead of returning infinity?

If I reformat the method to

double divide(double a, double b)
{
    if ( b == 0 )
    {
        throw new ArgumentException("Argument b must be non zero.", new DivideByZeroException());
    }
    return a / b;
}

would the new DivideByZeroException contain all the same information and structure that the caught exception would?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It's because you use System.Double.

As stated by MSDN DivideByZeroException is thrown only for integral types and Decimal.

That's because it is hard to define "so called" zero for Double value.

PositiveInfinity also results from a division by zero with a positive dividend, and NegativeInfinity results from a division by zero with a negative dividend. (source: MSDN again)

DivideByZeroException is not appropriate for floating point types. Note: You can get NaN though when attempting to divide by zero with a dividend of zero.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...