Skip to content
Tutorials Center
My learning

Topics

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.

C#
int a = 10, b = 0;
int result = b != 0 ? a / b : 0;

Try it

C# Integer, decimal and floating-point division

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.

C# Guarding the divisor

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

C#
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. NaN and Infinity spread through later calculations silently. Test with double.IsFinite.
  • Enumerable.Average on an empty sequence throws InvalidOperationException, not this exception.
  • int.MinValue / -1 throws OverflowException, not DivideByZeroException, 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 ArithmeticException if 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, 0 or throws a clearer domain exception.