Divide by Zero Exception in C#: DivideByZeroException, Infinity and NaN (.NET 10)

Here’s the line that takes down a sales report: totalSales / orders on a region with zero orders. With int values it throws a divide by zero exception in C#; switch both to double and it quietly prints ∞ instead.

Quick answer: integer and decimal division by zero throw DivideByZeroException, so check the divisor first. double and float return ∞, -∞ or NaN, so test the result with double.IsFinite.

Below is how we handle both on .NET 10, using a real regional sales report in USD.

What You Need Before You Start Testing Division by Zero

  • The .NET 10 SDK; each file runs with dotnet run File.cs (VS Code console app setup).
  • The sample: average order value per region (Texas, Ohio, Vermont) in USD, with the en-US culture set.

Step 1: Reproduce the DivideByZeroException with int Division

This is the code from the hook. Vermont launched this week, so its order count is still 0:

int totalSales = 4_870;   // dollars
int orders = 0;           // Vermont: no orders yet

int average = totalSales / orders;
Console.WriteLine($"Average order: ${average}");

Output:

Unhandled exception. System.DivideByZeroException: Attempted to divide by zero.
   at Program.<Main>$(String[] args) in C:\DotNetDemo\DivZero\AverageOrder.cs:line 4
C# int division by zero throwing an unhandled System.DivideByZeroException: Attempted to divide by zero, in the VS Code terminal on .NET 10
int division by zero crashes the program with an unhandled DivideByZeroException

The process exits at line 4 with Attempted to divide by zero., because the int data type in C# has no value for infinity.

Step 2: See Why double Division by Zero Returns ∞ or NaN

Change the same numbers to double and nothing throws. Floating-point types follow the IEEE 754 standard, which defines infinity and NaN (not a number):

using System.Globalization;
CultureInfo.CurrentCulture = CultureInfo.GetCultureInfo("en-US");

double sales = 4_870.0;
double orders = 0;

Console.WriteLine($"sales / 0   = {sales / orders}");
Console.WriteLine($"-sales / 0  = {-sales / orders}");
Console.WriteLine($"0.0 / 0     = {0.0 / orders}");
Console.WriteLine($"as currency = {(sales / orders):C2}");

double avg = sales / orders;
Console.WriteLine($"IsNaN(0/0): {double.IsNaN(0.0 / orders)}");
Console.WriteLine($"IsFinite:   {double.IsFinite(avg)}");
Console.WriteLine($"x == NaN:   {0.0 / orders == double.NaN}");

Output:

sales / 0   = ∞
-sales / 0  = -∞
0.0 / 0     = NaN
as currency = ∞
IsNaN(0/0): True
IsFinite:   False
x == NaN:   False
C# double division by zero printing ∞, -∞ and NaN with double.IsInfinity, double.IsNaN and double.IsFinite checks in VS Code
double and float return ∞, -∞ or NaN instead of throwing

A positive number over zero gives ∞, a negative one -∞, and 0.0 / 0 gives NaN; float behaves the same. Even the C2 currency format prints ∞, so a bad average sneaks into the report.

Test the result with double.IsFinite or double.IsNaN, never == double.NaN. The same applies when you convert a string to double from user input.

Step 3: Know Which Types Throw DivideByZeroException

What matters is the type of the division, not where you store the result. I ran each operator against a run-time zero:

using System.Globalization;
CultureInfo.CurrentCulture = CultureInfo.GetCultureInfo("en-US");

int zero = 0;
Check("int /", () => 10 / zero);
Check("long /", () => 10L / zero);
Check("decimal /", () => 10m / zero);
Check("int %", () => 10 % zero);
Check("double /", () => 10.0 / zero);
Check("double %", () => 10.0 % zero);

static void Check(string op, Func<object> divide)
{
    try { Console.WriteLine($"{op,-10} {divide()}"); }
    catch (DivideByZeroException) { Console.WriteLine($"{op,-10} DivideByZeroException"); }
}

Output:

int /      DivideByZeroException
long /     DivideByZeroException
decimal /  DivideByZeroException
int %      DivideByZeroException
double /   ∞
double %   NaN

int, long and decimal throw, and so does % on them. byte and short throw too, since C# promotes them to int first (see type casting in C#).

double gives ∞ and NaN instead. One double operand is enough: 10.0 / zero never throws.

Why Is Dividing by a Constant Zero a Compile Error (CS0020)?

When the divisor is a literal or const zero, the compiler evaluates the expression itself and refuses to build:

const int Regions = 0;

int perRegion = 4_870 / Regions;
decimal share = 4_870m % 0m;
double ratio = 4_870.0 / 0;   // compiles: double gives ∞

Console.WriteLine($"{perRegion} {share} {ratio}");

Build output:

C:\DotNetDemo\DivZero\ConstantZero.cs(3,17): error CS0020: Division by constant zero
C:\DotNetDemo\DivZero\ConstantZero.cs(4,17): error CS0020: Division by constant zero

The build failed. Fix the build errors and run again.
C# error CS0020 Division by constant zero for an int const and a decimal remainder, while double division by a constant zero compiles, in VS Code
CS0020 catches int and decimal division by a constant zero; the double line compiles

The int and decimal % lines fail; the double line compiles. So the exception always comes from a run-time value, like user input or a database count.

Step 4: Check the Divisor Before You Divide (Recommended)

A new region with zero orders is normal, not a bug. Microsoft’s guidance is to check routine conditions instead of catching exceptions, so we test Orders == 0 first:

using System.Globalization;
CultureInfo.CurrentCulture = CultureInfo.GetCultureInfo("en-US");

var regions = new (string Name, decimal Sales, int Orders)[]
{
    ("Texas", 18_420.50m, 214),
    ("Ohio", 7_315.00m, 96),
    ("Vermont", 0m, 0),
};

foreach (var r in regions)
{
    string avg = r.Orders == 0
        ? "n/a (no orders)"
        : (r.Sales / r.Orders).ToString("C2");
    Console.WriteLine($"{r.Name,-8} {avg}");
}

Output:

Texas    $86.08
Ohio     $76.20
Vermont  n/a (no orders)
C# region report checking the order count before dividing, printing average order value in USD for Texas and Ohio and n/a for Vermont
Checking the divisor first: Texas and Ohio get an average, Vermont gets n/a

Texas averages $86.08 and Ohio $76.20, and Vermont prints n/a (no orders) with no exception. The data lives in a tuple array, and decimal keeps the cents exact.

Step 5: Catch DivideByZeroException with try/catch

Use try/catch when the zero comes from code you don’t control and you can still recover, like skipping one bad day in a batch:

int[] dailyOrders = [42, 0, 36];
int adBudget = 1_260;

foreach (int orders in dailyOrders)
{
    try
    {
        Console.WriteLine($"Ad cost per order: ${adBudget / orders}");
    }
    catch (DivideByZeroException ex)
    {
        Console.WriteLine($"Skipped a day: {ex.Message}");
    }
}

Output:

Ad cost per order: $30
Skipped a day: Attempted to divide by zero.
Ad cost per order: $35

Day 1 costs $30 per order, day 2 is skipped with the exception’s message, and day 3 costs $35. Catch DivideByZeroException by name, not plain Exception; the try-catch in C# guide covers ordering several catch blocks.

Step 6: Write a Safe Divide Helper

When the same check shows up in five places, I move it into a few small functions in C#. Decide what zero should mean for you:

using System.Globalization;
CultureInfo.CurrentCulture = CultureInfo.GetCultureInfo("en-US");

Console.WriteLine(SafeDivide(18_420.50m, 214m)?.ToString("C2") ?? "n/a");
Console.WriteLine(SafeDivide(0m, 0m)?.ToString("C2") ?? "n/a");
Console.WriteLine(SafeRatio(37.0, 0.0));

try { Console.WriteLine(Average(4_870m, 0)); }
catch (ArgumentOutOfRangeException ex) { Console.WriteLine(ex.Message); }

static decimal? SafeDivide(decimal a, decimal b) => b == 0 ? null : a / b;

static double SafeRatio(double a, double b, double fallback = 0)
{
    double r = a / b;
    return double.IsFinite(r) ? r : fallback;
}

static decimal Average(decimal total, int count)
{
    ArgumentOutOfRangeException.ThrowIfZero(count);   // .NET 8+
    return total / count;
}

Output:

$86.08
n/a
0
count ('0') must be a non-zero value. (Parameter 'count')
Actual value was 0.

SafeDivide returns null for a zero decimal divisor, and SafeRatio turns ∞ and NaN into a fallback of 0. When a zero count really is a bug, ArgumentOutOfRangeException.ThrowIfZero (.NET 8+) fails fast with a clear message instead.

Division by Zero in C#: Cheat Sheet

The table we keep for code reviews:

ExpressionRun-time zeroConstant zero
int / long / or %DivideByZeroExceptionCS0020
decimal / or %DivideByZeroExceptionCS0020
double / float x / 0∞ or -∞Compiles
double 0.0 / 0 or x % 0NaNCompiles

Common Mistakes to Avoid with Divide by Zero

MistakeWhat happensFix
Casting after dividing: (double)(a / b)Integer division runs first and still throwsCast one operand: (double)a / b
Expecting double to throw∞ or NaN flows into totals and reportsCheck double.IsFinite
x == double.NaNAlways falsedouble.IsNaN(x)
try/catch around every divisionSlower, and hides the real causeCheck the divisor first

The first row trips up beginners most often; the add, subtract, multiply and divide program shows why 7 / 2 is 3 in C#.

Next Steps

For money, use decimal with a divisor check; for measurements, use double and test with double.IsFinite. Then make the results look right with number formatting with commas and decimals.

We’d read these next:

Frequently Asked Questions

Does dividing a double by zero throw an exception in C#?

No. double and float division by zero returns positive infinity, negative infinity or NaN under IEEE 754 rules. Only integer and decimal division throw DivideByZeroException.

Why does my C# code show ∞ instead of Infinity?

The infinity text comes from the current culture’s NumberFormatInfo.PositiveInfinitySymbol. With en-US on .NET 10, that symbol is ∞.

Should I use try/catch or an if check for division by zero?

Use an if check when zero is a normal value, such as a region with no orders. Use try/catch only when you can’t check first and can still recover.

What is the base class of DivideByZeroException?

ArithmeticException, which derives from SystemException. The DivideByZeroException page on Microsoft Learn lists the full hierarchy.

Is there a built-in safe divide method in .NET?

No. Write a small helper, or call ArgumentOutOfRangeException.ThrowIfZero to fail fast. The arithmetic operators reference covers every division rule.