【问题标题】:_controlfp does not prevent DivideByZeroException_controlfp 不会阻止 DivideByZeroException
【发布时间】:2023-03-03 02:19:01
【问题描述】:

我用 C# 写了以下几行

using System;
using System.Runtime.InteropServices;

namespace ConsoleApplication1
{
    class Program
    {
        [DllImport("msvcrt.dll", CallingConvention = CallingConvention.Cdecl)]
        extern static uint _controlfp(uint newcw, uint mask);

        const uint _MCW_EM = 0x0008001f;
        public const uint EM_INVALID = 0x00000010;
        public const uint EM_DENORMAL = 0x00080000;
        public const uint EM_ZERODIVIDE = 0x00000008;
        public const uint EM_OVERFLOW = 0x00000004;
        public const uint EM_UNDERFLOW = 0x00000002;
        public const uint EM_INEXACT = 0x00000001;

        static void MaskFpu(uint pExceptionMask = EM_INVALID)
        {
            // add desired values
            _controlfp(_MCW_EM, pExceptionMask);
        }

        static void Main(string[] args)
        {
            MaskFpu(EM_ZERODIVIDE);

            int a = 0;
            var b = 5/a;

            Console.WriteLine("b = " + b);
        }
    }
}

Main 方法从设置控制字开始。显然我希望 DivideByZeroExceptions 被屏蔽。

在执行 _controlfp 之后,我预计除以零会返回 NaN。但是var b = 5 / a 会引发异常。

我怎样才能真正防止我的流程引发 DivideByZeroExceptions?

【问题讨论】:

  • 如果您实际上只是在测试中使用了浮点类型,那么您将不需要任何这种容易出错的遗留垃圾。试试看。
  • 我希望 controlfp 控制 floating-point 操作 - 您正在执行整数操作。尝试使用0.05.0 看看是否对您有帮助...
  • 也许this 会有所帮助:“随后可以通过调用 _ _controlfp(EM_ZERODIVIDE, EM_ZERODIVIDE) 来禁用除零异常”
  • 感谢您的回复。如果我将int 替换为double,则该掩码确实有效。不幸的是,您的建议不适用于我的示例 DGibbs。 :(

标签: c# exception dllimport divide-by-zero floating-point-exceptions


【解决方案1】:
int a = 0;
var b = 5/a;

您在此处执行整数运算,因此屏蔽浮点异常对此表达式没有影响。

【讨论】:

    猜你喜欢
    • 2020-07-10
    • 2019-01-28
    • 2019-08-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多