我们在客户机器上的以下行中得到一个ArithmeticException(算术运算中上溢或下溢。)。我们无法在任何 PC(客户或我们的)上复制它:
var actualFullness = (byte)((hdd.Capacity - hdd.FreeSpace) / (float)hdd.Capacity * 100);
其中 hdd.Capacity
和 hdd.FreeSpace
是 uint
。值来自 native DLL 中的函数。
我们在程序中不使用checked
或unchecked
关键字。我们不使用 /checked 编译器选项。
它是用 .NET 4 编写的,作为 32 位进程运行。
知道为什么抛出这个异常吗?
最佳答案
问题中显示的算术不会引发异常。这个程序涵盖了边缘情况并且运行得很好:
class Program
{
static byte test(uint capacity, uint free)
{
return (byte)((capacity - free) / (float)capacity * 100);
}
static void Main(string[] args)
{
Console.WriteLine(test(uint.MaxValue, uint.MaxValue));
Console.WriteLine(test(0, 0));
Console.WriteLine(test(uint.MaxValue, 0));
Console.WriteLine(test(0, uint.MaxValue));
}
}
事实上,通过静态分析很容易看出问题中的表达式不是造成错误的原因。
看来你确实误诊了故障。也许您引用的 native 代码以某种方式触发了异常。无论如何,唯一要说的是,您需要深入挖掘并尝试获得对问题的正确诊断。
关于c# - C# 中未检查代码中的 ArithmeticException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23239731/