_controlfp does not prevent DivideByZeroException
本文关键字:prevent DivideByZeroException not does controlfp | 更新日期: 2023-09-27 17:52:56
我用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?
int a = 0;
var b = 5/a;
您在这里执行整数运算,因此屏蔽浮点异常对该表达式没有影响。