C# Reference ยท Exceptions and Diagnostics
DivideByZeroException
Reference for DivideByZeroException in C#: integer and decimal division by zero, why floating point returns Infinity, and how to guard divisors.
DivideByZeroException is thrown when you divide an integer or a decimal by zero, or take the remainder with a zero divisor: 10 / 0, 10 % 0, 5m / 0m. It derives from ArithmeticException.
Floating-point types behave differently. double and float follow the IEEE 754 rules: 1.0 / 0 is Infinity, -1.0 / 0 is -Infinity and 0.0 / 0 is NaN, with no exception. The best fix is to check the divisor before dividing; catching the exception is only appropriate at a boundary where you cannot control the input.
int a = 10, b = 0; int result = b != 0 ? a / b : 0;
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.
Syntax
public class DivideByZeroException : ArithmeticException { public DivideByZeroException(); public DivideByZeroException(string? message); public DivideByZeroException(string? message, Exception? innerException); }
| Expression | Result |
|---|---|
int / 0, long / 0, int % 0 |
Throws DivideByZeroException. |
decimal / 0m, decimal % 0m |
Throws DivideByZeroException. |
double / 0.0 (non-zero numerator) |
Infinity or -Infinity. |
0.0 / 0.0, double % 0.0 |
NaN. |
Constant 10 / 0 |
Compile error CS0020: Division by constant zero. |
The message is "Attempted to divide by zero."
Usage notes
- Check, do not catch.
if (divisor != 0)costs nothing; throwing and catching is slow and hides the intent. - Typical sources: averages of empty collections, percentages with a zero total, per-unit rates with zero quantity, and modulo by a user-supplied size.
- Floating-point is not safe by default.
NaNandInfinityspread through later calculations silently. Test withdouble.IsFinite. Enumerable.Averageon an empty sequence throwsInvalidOperationException, not this exception.int.MinValue / -1throwsOverflowException, notDivideByZeroException, because the true result does not fit.- Compile-time detection. Literal zero divisors are rejected by the compiler, so runtime tests need a variable.
- Catch the base type
ArithmeticExceptionif you want to handle both division and overflow errors in one place. - Unit tests: assert that code handles the zero case explicitly, for example returns
null,0or throws a clearer domain exception.