Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Zero division does not throw exception in nunit

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?

like image 463
Boris Avatar asked May 31 '10 19:05

Boris


People also ask

How do you throw a divide by zero exception?

using System; public class Example { public static void Main() { int number1 = 3000; int number2 = 0; try { Console. WriteLine(number1 / number2); } catch (DivideByZeroException) { Console. WriteLine("Division of {0} by zero.", number1); } } } // The example displays the following output: // Division of 3000 by zero.

How do I catch exceptions in Nunit?

Throws( Is. InstanceOf<ApplicationException>(), code ); // Allow both ApplicationException and any derived type Assert. Catch<ApplicationException>( code ); // Allow any kind of exception Assert. Catch( code );

Is the base class for divide by zero exception?

Any number divided by zero gives the answer “equal to infinity.” Unfortunately, no data structure in the world of programming can store an infinite amount of data. Hence, if any number is divided by zero, we get the arithmetic exception .

Which exception raised when a denominator is having zero value in division Mcq?

ZeroDivisionError: It is raised when the denominator in a division operation is zero.


1 Answers

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.

like image 157
Joren Avatar answered Oct 11 '22 14:10

Joren