0

When I am initializing a variable to zero, like int i=0, it throws an exception:

Attempt to divide by zero

How is this possible? The exception is thrown in other cases, also, like getting zero indexed value from a collection: collection[0], and if(a%b==0) etc,.

Please suggest how I can deal with this.

Michael Petrotta
  • 59,888
  • 27
  • 145
  • 179
CP17071989
  • 1
  • 1
  • 1
  • Dividing by zero (either with standard division or modulus) will through a `DivideByZeroException`. If you don't want to get that exception check that your divisor isn't zero before dividing. – shf301 Jan 29 '14 at 04:16

2 Answers2

3

DivideByZeroException:

The exception that is thrown when there is an attempt to divide an integral (such as int or long) or decimal value by zero.

This exception will also be thrown in the case of a % b if b evaluates to 0.

Either

  1. Guard the expression such that 0 is never used in the division/modulo, or;

  2. Catch the exception (ick)

user2864740
  • 60,010
  • 15
  • 145
  • 220
  • 2
    +1 for providing both options, guarding is the best solution. If this is happening regularly in your code it might be better to use a function `Divide(int a, int b)` to perform the guarding so you don't repeat yourself and dont forget to guard. – Matthew Pigram Jan 29 '14 at 04:36
1

You need to catch your Exception and handle it properly.

try
{
   // your code that throws exception
}
catch (DivideByZeroException ex)
{
   // Perform an appropriate action
   // for example display a custom message
   Console.WriteLine(ex.Message);
}

For more information see: Exceptions and Exception Handling

Selman Genç
  • 100,147
  • 13
  • 119
  • 184