_controlfp 不会阻止 DivideByZeroException

_controlfp does not prevent DivideByZeroException

我在 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 之后,我预计除以零会 return NaN。但是 var b = 5 / a 引发了异常。

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

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

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