c# - C# 中未检查代码中的 ArithmeticException

标签 c# .net-4.0 checked unchecked arithmeticexception

我们在客户机器上的以下行中得到一个ArithmeticException(算术运算中上溢或下溢。)。我们无法在任何 PC(客户或我们的)上复制它:

var actualFullness = (byte)((hdd.Capacity - hdd.FreeSpace) / (float)hdd.Capacity * 100);

其中 hdd.Capacityhdd.FreeSpaceuint。值来自 native DLL 中的函数。

我们在程序中不使用checkedunchecked 关键字。我们不使用 /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/

相关文章:

c# - 为什么我对 Google 自定义搜索 API 的调用失败并显示请求错误(无效参数)?

.net - 如何将 CheckedListBox.checkedItems 作为字符串列表

c# - 创建 WCF PUT Rest 服务

php - 是否在检查 radio 时检查

Jquery Jstree复选框事件捕获

c# - 在不捕获异常的情况下使用额外信息注释异常

c# - 按钮单击 c# 中的代码发生在函数完成之后

jquery - 如果选中复选框,请执行此操作

c# - 我可以在 .NET Framework 4.0 上运行 MVC 5 应用程序吗?

.net-4.0 - .NET 4.0 - CultureNotFoundException