# Why is division by zero not throwing exception

#### mp3909

##### Well-known member
As the title explains, I would have excepted an exception on this line

C#:
``float result = fn / (float)sn;``

if fn = 45 and sn = 0

In that code there, you are doing floating point division, not integer division. That result you are getting is an infinity symbol, not an 8.

As the DivideByZeroException documentation says:
Trying to divide an integer or Decimal number by zero throws a DivideByZeroException exception. To prevent the exception, ensure that the denominator in a division operation with integer or Decimal values is non-zero.

Dividing a floating-point value by zero doesn't throw an exception; it results in positive infinity, negative infinity, or not a number (NaN), according to the rules of IEEE 754 arithmetic

ok, but how do I still a maintain floating point division that also kicks back an exception when someone tries to do division by zero?

I think I know the answer, cast it as decimal instead of float

I think I know the answer, cast it as decimal instead of float
Uh, no. The thing to do would be to test the value you're dividing by first and don't do it if it's zero. Prevention is almost always better than cure.

You can also test result with float.IsInfinity.

ok, but how do I still a maintain floating point division that also kicks back an exception when someone tries to do division by zero?
Why? Are you porting code from another language which does throw division by zero exceptions and you want to try to keep the ported close as close to the original code as possible?

Uh, no. The thing to do would be to test the value you're dividing by first and don't do it if it's zero. Prevention is almost always better than cure.
Thanks jmcilhinney

Why? Are you porting code from another language which does throw division by zero exceptions and you want to try to keep the ported close as close to the original code as possible?
No, this is me just trying to practice C# and figuring out ways to do stuff.

Replies
6
Views
959
Replies
4
Views
550
Replies
3
Views
725
Replies
6
Views
314
Replies
3
Views
649