Divide by zero and no error?

It just compiled a simple test, and not for any specific reason, except I wanted to try the tests for all my methods, although this is pretty simple, or so I thought.

[TestMethod] public void Test_GetToolRating() { var rating = GetToolRating(45.5, 0); Assert.IsNotNull(rating); } private static ToolRating GetToolRating(double total, int numberOf) { var ratingNumber = 0.0; try { var tot = total / numberOf; ratingNumber = Math.Round(tot, 2); } catch (Exception ex) { var errorMessage = ex.Message; //log error here //var logger = new Logger(); //logger.Log(errorMessage); } return GetToolRatingLevel(ratingNumber); } 

As you can see in the testing method, I divide by zero. The problem is that it does not generate an error. See Error Window Screen below.

View a list of errors from VS2017

Instead of error, does it give the meaning of infinity? What am I missing? So I searched googled and found that doubles divided by zero DO NOT generate an error, they either give zero or infinity. The question then becomes, how is one test for the return value of Infinity?

+43
c # divide-by-zero
May 30 '17 at 9:14 a.m.
source share
2 answers

You will have a DivideByZeroException only in case of integer values:

 int total = 3; int numberOf = 0; var tot = total / numberOf; // DivideByZeroException thrown 

If at least one argument is a floating point value ( double in the question), as a result you will get FloatingPointType.PositiveInfinity ( double.PositiveInfinity in context) and an exception

 double total = 3.0; int numberOf = 0; var tot = total / numberOf; // tot is double, tot == double.PositiveInfinity 
+74
May 30 '17 at 9:20 a.m.
source share

You can check as below

 double total = 10.0; double numberOf = 0.0; var tot = total / numberOf; // check for IsInfinity, IsPositiveInfinity, // IsNegativeInfinity separately and take action appropriately if need be if (double.IsInfinity(tot) || double.IsPositiveInfinity(tot) || double.IsNegativeInfinity(tot)) { ... } 
+6
May 30 '17 at 9:24 a.m.
source share



All Articles