为什么这个方法返回double.PositiveInfinity不是DivideByZeroException?

Kel*_*all 11 c# exception-handling infinity dividebyzeroexception

我在VS2015 C#interactive中运行了以下代码片段并得到了一些非常奇怪的行为.

> 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.
> 
Run Code Online (Sandbox Code Playgroud)

为什么该方法返回无穷大而3/0引发错误并且3/b抛出格式化错误?我可以强制分裂抛出错误而不是返回无穷大吗?

如果我重新格式化方法

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

新的DivideByZeroException是否包含捕获的异常所具有的所有相同信息和结构?

Ser*_*nov 19

这是因为你使用System.Double.

正如MSDN 所述,DivideByZeroException仅针对整数类型而抛出Decimal.

那是因为很难为Double值定义"所谓的"零.

PositiveInfinity也是由零除以正股息产生的,而NegativeInfinity是由零除以负股息产生的.(来源:MSDN再次)

DivideByZeroException不适用于浮点类型.注意:NaN当试图用零除以零时,你可以得到.