零除法不会在 nunit 中引发异常
通过 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
没有抛出异常。 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.
来自 MSDN:
您正在处理
double,
而不是任何整数类型(int
等)或decimal
。即使在checked
上下文中,double
也不会抛出异常。你只需得到+INF。如果您想计算积分数学(并获得例外),请使用:
From MSDN:
You are dealing with
double,
not any of the integral types (int
etc) ordecimal
.double
doesn't throw an exception here, even in achecked
context. You just get +INF.If you want to evaluate as integral math (and get the exception), use: