PositiveInfinity不是DivideByZeroEx

PositiveInfinity不是DivideByZeroEx

本文介绍了为什么这个方法返回double.PositiveInfinity不是DivideByZeroException?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 29岁程序员,3月因学历无情被辞! > 我在VS2015 C#交互中运行了以下代码片段,并获得了一些非常奇怪的行为。双分(双a,双b)。 {。尝试。 {。返回a / b; 。 } 。 catch(DivideByZeroException异常)。 {。抛出新的ArgumentException(参数b必须为非零,异常); 。 } 。 } >除(3,0)无限> 3/0 (1,1):错误CS0020:除以常数零> var b = 0; > 3 / b 尝试除以零。 > 为什么方法返回无穷大,而3/0抛出错误,3 / b抛出一个格式错误?我可以强制分裂抛出一个错误,而不是返回无穷远? 如果我将方法重新格式化为 抛出新的ArgumentException(参数b必须非零。,新的DivideByZeroException()); } 返回a / b;新的DivideByZeroException将包含所有相同的信息和结构,即捕获的异常将会被捕获,例如} 解决方案这是因为您使用System.Double。 由 MSDN DivideByZeroException仅针对整数类型和十进制抛出。 这是因为很难为Double值定义所谓为零。 PositiveInfinity还产生了一个零除以正的股利,NegativeInfinity由零除以的负股息结果。 (来源: MSDN再次) DivideByZeroException不适用于浮点类型。注意:尽管尝试将零除以零,但您可以获得 NaN 。 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 / bAttempted 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 todouble 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? 解决方案 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. 这篇关于为什么这个方法返回double.PositiveInfinity不是DivideByZeroException?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!
08-24 09:04