零除法不会在 nunit 中引发异常

发布于 2024-09-03 19:29:54 字数 753 浏览 5 评论 0原文

通过 NUnit 运行以下 C# 代码会产生结果

Test.ControllerTest.TestSanity: Expected: `<System.DivideByZeroException>` But was:  null

因此,要么不会抛出 DivideByZeroException,要么 NUnit 不会捕获它。类似于 this 问题,但他得到的答案是似乎不适合我。这是使用 NUnit 2.5.5.10112 和 .NET 4.0.30319。

    [Test]
    public void TestSanity()
    {
        Assert.Throws<DivideByZeroException>(new TestDelegate(() => DivideByZero()));
    }

    private void DivideByZero()
    {
        // Parse "0" to make sure to get an error at run time, not compile time.
        var a = (1 / Double.Parse("0"));
    }

有什么想法吗?

Running the following C# code through NUnit yields

Test.ControllerTest.TestSanity: Expected: `<System.DivideByZeroException>` But was:  null

So either no DivideByZeroException is thrown, or NUnit does not catch it. Similar to this question, but the answers he got, do not seem to work for me. This is using NUnit 2.5.5.10112, and .NET 4.0.30319.

    [Test]
    public void TestSanity()
    {
        Assert.Throws<DivideByZeroException>(new TestDelegate(() => DivideByZero()));
    }

    private void DivideByZero()
    {
        // Parse "0" to make sure to get an error at run time, not compile time.
        var a = (1 / Double.Parse("0"));
    }

Any ideas?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

梦在深巷 2024-09-10 19:29:54

没有抛出异常。 1 / 0.0 只会给你 double.PositiveInfinity。这是 IEEE 754 标准指定的内容,C#(以及基本上所有其他系统)也遵循该标准。

如果您希望浮点除法代码中出现异常,请显式检查零,然后自行抛出异常。如果您只是想看看 DivideByZeroException 会得到什么,可以手动抛出它或将整数除以整数零。

No exception is thrown. 1 / 0.0 will just give you double.PositiveInfinity. This is what the IEEE 754 standard specifies, which C# (and basically every other system) follows.

If you want an exception in floating point division code, check for zero explicitly, and throw it yourself. If you just want to see what DivideByZeroException will get you, either throw it manually or divide integers by integer zero.

没有心的人 2024-09-10 19:29:54

来自 MSDN

尝试将整数或小数值除以零时引发的异常。

您正在处理double,而不是任何整数类型(int等)或decimal。即使在 checked 上下文中,double 也不会抛出异常。你只需得到+INF。

如果您想计算积分数学(并获得例外),请使用:

var a = (1 / int.Parse("0"));

From MSDN:

The exception that is thrown when there is an attempt to divide an integral or decimal value by zero.

You are dealing with double, not any of the integral types (int etc) or decimal. double doesn't throw an exception here, even in a checked context. You just get +INF.

If you want to evaluate as integral math (and get the exception), use:

var a = (1 / int.Parse("0"));
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文