System.DivideByZeroException
A DivideByZeroException is thrown when an integer or decimal value is divided by zero. The message is Attempted to divide by zero. It applies to the / and % operators.
Floating point numbers behave differently. Dividing a double by zero does not throw. The result is Infinity or NaN, which can travel through your calculations unnoticed until it shows up in a result.
Minimum version: >= 1.1 >= Core 1.0
Statistics
Common causes
The divisor was zero at runtime. These are the places where it usually comes from.
Dividing by a count that can be zero
An average of an empty list divides the total by a count of zero. The same happens with percentages of an empty total.
var total = 100;
var count = 0;
var average = total / count; // DivideByZeroException
Handle the empty case explicitly:
var total = 100;
var count = 0;
var average = count == 0 ? 0 : total / count;
The modulo operator
The remainder operator % divides too, so a divisor of zero throws. Paging code that calculates a page number from a page size is a common place.
var pageSize = 0; // a setting that was not configured
var remainder = 25 % pageSize; // DivideByZeroException
Validate settings when the application starts, and fall back to a sensible default:
var pageSize = 0;
if (pageSize <= 0)
{
pageSize = 10;
}
var remainder = 25 % pageSize;
Decimal division
decimal is a floating point type, but it throws. Money calculations that divide by a quantity fail when the quantity is zero.
decimal price = 99.50m;
decimal quantity = 0m;
var unitPrice = price / quantity; // DivideByZeroException
Check the divisor before you divide:
decimal price = 99.50m;
decimal quantity = 0m;
var unitPrice = quantity == 0m ? 0m : price / quantity;
How to fix it and prevent it
Check the divisor
A condition before the division is the simplest fix. Decide what the result should be when the divisor is zero. It is often zero, null, or a message to the user.
static decimal Percentage(int part, int total)
{
if (total == 0)
{
return 0;
}
return (decimal)part / total * 100;
}
Use LINQ methods that handle empty sequences
Average throws an InvalidOperationException on an empty sequence of numbers. DefaultIfEmpty gives it a value to work with.
var ids = new List<int>();
var average = ids.DefaultIfEmpty(0).Average();
Know what floating point does
If you use double, check the result with double.IsInfinity or double.IsNaN. Otherwise an infinite value can reach a database or a report.
double ratio = 5.0 / 0; // Infinity, no exception
if (double.IsInfinity(ratio) || double.IsNaN(ratio))
{
Console.WriteLine("The ratio is not a valid number.");
}
How to find the zero
The stack trace points to the line with the division:
System.DivideByZeroException: Attempted to divide by zero.
at Shop.Services.Stats.Average(Int32 total, Int32 count) in C:\src\Shop\Services\Stats.cs:line 6
at Program.<Main>$(String[] args) in C:\src\Shop\Program.cs:line 4
Line 6 of Stats.cs is total / count. The exception does not say which operand was zero, but the divisor is the right-hand side. Check where it comes from. Often it is an empty collection, or a setting that was never configured.
Should you catch it?
Usually not. A zero divisor is a case you can check for, and checking is clearer and cheaper than catching.
If the divisor comes from data you do not control, validate it where it enters your application. Catch the exception only at the edge, where unexpected failures are logged.
Find DivideByZeroException before your users do
elmah.io logs every unhandled exception in your .NET application with its stack trace and request details, groups identical errors and notifies you when a new one appears.
Start free trialRelated exceptions
- ArithmeticException is the base class, shared with
OverflowException. - OverflowException is thrown when a result does not fit in the target type.
Frequently asked questions
Why does dividing a double by zero not throw?
Floating point numbers follow the IEEE 754 standard, which defines the results Infinity, -Infinity and NaN. Integers and decimal have no such values, so they throw.
Does the modulo operator throw too?
Yes, for integers and decimal. x % 0 throws a DivideByZeroException.
How do I find which value was zero?
Look at the right-hand side of the division on the line in the stack trace, and log both operands when the divisor can come from data. A DivideByZeroException does not include the values.
Should I catch DivideByZeroException?
Normally not. Check the divisor first. If you do catch it, log the operands, so you can find the data that caused it.
Let your AI agent track it down
Connect Claude Code, Cursor, VS Code or Visual Studio to the elmah.io MCP server and ask your agent to look into DivideByZeroException for you. For example:
The agent reads the stack trace and request details from elmah.io, finds the code in your repository and proposes a fix. In Claude Code, add the server with one command:
claude mcp add --transport http --client-id claudecode elmahio https://mcp.elmah.io/mcp
The MCP server is included on every plan and is currently in beta. Set up the MCP server.
Further reading
YouTube videos
Answers from Stack Overflow
You should get all of this by simply calling the .ToString() method of the exception. We use this to log information and you get everything that I believe you are asking for. See MSDN System.Exception.ToString() for more information.
By Zach Bonham. Read the original answer on Stack Overflow.
The reason of divide by zero here is not really related to truncating result when casting Math.Pow(x, 0) to int. Math.Pow(x, 0) will always return 1, and casting it to int will give you 1. Reason is integer overflow. For example consider:
var pow = (int)Math.Pow(10, 10);
10^10 does not fit into int size, so it will overflow (multiple times), and variable pow will have value -2147483648. When you multiply that by 10, it again overflows and result is 0. At this point you get your divide by zero exception.
To avoid such bizzare results you might want to do arithmetic operations that might unexpectedly result in overflow in checked context:
checked {
var pow = (int) Math.Pow(10,10);
// throws overflow exception so you can fix your buggy code early
}
Of course at that point you already realize that your algorithm to reverse number is not a good one, so refer to another answer for a better way.
You are encountering limitations of computer-based arithmetic. (Another answer shows the details which I were incorrect in previous versions of my answer.) To avoid these details entirely, you can divide by 10 at the end of each iteration of the loop:
while (x > 0)
{
int endDig = x % 10;
//...
x /= 10;
}
Now you no longer need to worry the limits of int because your number will never be larger than the original input.
By Code-Apprentice. Read the original answer on Stack Overflow.
I got something working by emitting an (in-memory) assembly with debug information.
Example code:
var code = @"
var a = 0;
var b = 1 / a;
";
var script = CSharpScript.Create(code);
var compilation = script.GetCompilation();
var ilstream = new MemoryStream();
var pdbstream = new MemoryStream();
compilation.Emit(ilstream, pdbstream);
var assembly = Assembly.Load(ilstream.GetBuffer(), pdbstream.GetBuffer());
var type = assembly.GetType("Submission#0");
var factory = type.GetMethod("<Factory>");
var submissionArray = new object[2];
Task<object> task = (Task<object>)factory.Invoke(null, new object[] { submissionArray });
try
{
await task;
}
catch (DivideByZeroException dbze)
{
Console.WriteLine(dbze.StackTrace);
}
The output is (notice the :line 3 in the stack trace):
at Submission#0.<<Initialize>>d__0.MoveNext() in :line 3
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
at UnitTests.ExploreRoslyn.<ExploreEmittingAssembly>d__13.MoveNext() in D:\dev\misc\netmockery\UnitTests\ExploreRoslyn.cs:line 151
Now obviously this is a bit of a hack, and I'm not really happy with the hardcoded script engine implementation details (Submission#0, <Factory>), plus I don't really know what I'm doing. There should be (and maybe there is?) a better way.
Update
Created issue https://github.com/dotnet/roslyn/issues/13482 in the Roslyn issue tracker.
By codeape. Read the original answer on Stack Overflow.
There are two issues with your code:
In the first version, you're catching
Exception, which means that when theAssert.Failis reached and throwsAssertionException, that exception is then caught and ignored.This means that there is no difference between
RunAsyncand delegate here, neither of them throwsDivideByZeroException.Both
RunAsyncand theScriptRunner<T>delegate returnTask. That means to actually wait for them to complete or to observe any exceptions, you need to useawait. Once you do that, you will see theDivideByZeroExceptionthat you're expecting.
By svick. Read the original answer on Stack Overflow.
Source: Stack Overflow