System.ArithmeticException
An ArithmeticException is thrown for errors in arithmetic, casting and conversion. It is the base class of DivideByZeroException, OverflowException and NotFiniteNumberException, and in practice you almost always see one of those.
It is thrown directly in a few cases, for example when you ask for the sign of NaN. If you catch it, you also catch every one of the derived exceptions.
Minimum version: >= 1.1 >= Core 1.0
Statistics
Common causes
A bare ArithmeticException is rare. These are the cases you can run into.
The sign of NaN
Math.Sign cannot return a sign for a value that is not a number, so it throws the base exception. NaN is what you get from 0.0 / 0.0 or from parsing and calculations that went wrong earlier.
double change = double.NaN;
var direction = Math.Sign(change); // ArithmeticException: Function does not accept floating point Not-a-Number values.
Check for NaN before you ask for the sign:
double change = double.NaN;
var direction = double.IsNaN(change) ? 0 : Math.Sign(change);
A derived exception: OverflowException
Integer math that does not fit in the type throws the derived OverflowException. Math.Abs(int.MinValue) is an example, because the positive value does not exist in an int.
var value = int.MinValue;
var absolute = Math.Abs(value); // OverflowException
Use a larger type for the calculation:
var value = int.MinValue;
var absolute = Math.Abs((long)value);
A derived exception: DivideByZeroException
Integer and decimal division by zero throws the derived DivideByZeroException. Floating point division does not throw.
var total = 100;
var count = 0;
var average = total / count; // DivideByZeroException
Check the divisor before you divide:
var total = 100;
var count = 0;
var average = count == 0 ? 0 : total / count;
How to fix it and prevent it
Catch the specific exceptions first
If you handle arithmetic errors, catch DivideByZeroException and OverflowException before ArithmeticException. Then each case gets its own handling, and the base class is a fallback.
try
{
Calculate();
}
catch (DivideByZeroException)
{
Console.WriteLine("The divisor was zero.");
}
catch (OverflowException)
{
Console.WriteLine("The result does not fit in the type.");
}
catch (ArithmeticException e)
{
logger.LogError(e, "Unexpected arithmetic error");
}
static void Calculate() { }
Validate numbers before you calculate
Check for NaN and infinity with double.IsFinite when numbers come from outside your code. Reject them early instead of letting them travel through your calculations.
double ratio = 0.0 / 0.0;
if (!double.IsFinite(ratio))
{
Console.WriteLine("The ratio is not a valid number.");
}
Use checked arithmetic on purpose
Integer arithmetic wraps around silently by default. Use checked where a wrong result would be worse than an exception, and handle the OverflowException that follows.
var quantity = int.MaxValue;
var total = checked(quantity + 1);
How to find the cause
The stack trace shows which call threw. Here it is Math.Sign that received a NaN:
System.ArithmeticException: Function does not accept floating point Not-a-Number values.
at System.Math.Sign(Double value)
at Shop.Services.Scoring.Direction(Double change) in C:\src\Shop\Services\Scoring.cs:line 7
at Program.<Main>$(String[] args) in C:\src\Shop\Program.cs:line 4
The message tells you what was wrong with the input, and the line in your own code shows where the bad number was used. Follow the value backwards. A NaN usually comes from a division of zero by zero, or from a calculation on missing data.
Should you catch it?
Catch the specific exceptions, not ArithmeticException itself. Catching the base class also catches DivideByZeroException and OverflowException, which you probably want to treat differently.
Better still, avoid the exceptions by checking the inputs. Catching is for the edges of your application, where unexpected errors are logged.
Find ArithmeticException 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
- DivideByZeroException is a derived class, thrown when an integer or decimal is divided by zero.
- OverflowException is a derived class, thrown when a result does not fit in the target type.
- FormatException is thrown when text cannot be parsed into a number.
Frequently asked questions
When is ArithmeticException thrown directly?
Rarely. Math.Sign(double.NaN) is one example. In most code, the exception you see is DivideByZeroException or OverflowException.
Which exceptions derive from ArithmeticException?
DivideByZeroException, OverflowException and NotFiniteNumberException.
Why does integer overflow not throw by default?
In C#, arithmetic on integers is unchecked by default for speed, so values wrap around silently. Use the checked keyword, or the compiler option, to get an OverflowException instead.
Should I catch ArithmeticException?
Only as a fallback after the specific ones. It is better to validate the numbers before you calculate.
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 ArithmeticException 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
Following the link from @Mishhl the fix is
public class FloatingPointReset
{
[DllImport("msvcr110.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern int _fpreset();
public static void Action()
{
// Reset the Floating Point (When called from External Application there was an Overflow exception)
_fpreset();
}
}
It's caused by something in an included DLL resetting the FP into a state that isn't compatible with WPF/C#/Microsoft DLL's. Delphi/CPPB does this by default.
So in either the window constructor or App() constructor just do
FloatingPointReset.Action();
You may need to change the following to reference any version of msvcr###.dll
[DllImport("msvcr110.dll", CallingConvention = CallingConvention.Cdecl)]
e.g.
[DllImport("msvcr70.dll", CallingConvention = CallingConvention.Cdecl)]
By Richard Harrison. Read the original answer on Stack Overflow.
This usually occurs if the runtime system of the C dll changes FPU flags. You need to reset those after calling the function similar to this:
[DllImport("msvcrt.dll", CallingConvention = CallingConvention.Cdecl)]
extern static uint _controlfp(uint newcw,uint mask);
const uint _MCW_EM=0x0008001f;
const uint _EM_INVALID=0x00000010;
public static void FixFPU() {
{
_controlfp(_MCW_EM, _EM_INVALID);
}
By JeffRSon. Read the original answer on Stack Overflow.
My guess is that you're running out of memory in the byte[] array.
You can try breaking the file down and reading it in chunks.
I found a code example from a Google search to get you started:
C# file downloader AKA Response.BinaryWrite
using System;
using System.IO;
using System.Web;
public class Download
{
public static void SmallFile(string filename, string filepath, string contentType)
{
try
{
FileStream MyFileStream = new FileStream(filepath, FileMode.Open, FileAccess.Read, FileShare.Read);
long FileSize;
FileSize = MyFileStream.Length;
byte[] Buffer = new byte[(int)FileSize];
MyFileStream.Read(Buffer, 0, (int)MyFileStream.Length);
MyFileStream.Close();
HttpContext.Current.Response.ContentType = contentType;
HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(filename, System.Text.Encoding.UTF8));
HttpContext.Current.Response.BinaryWrite(Buffer);
}
catch
{
HttpContext.Current.Response.ContentType = "text/html";
HttpContext.Current.Response.Write("Downloading Error!");
}
HttpContext.Current.Response.End();
}
public static void LargeFile(string filename, string filepath, string contentType)
{
Stream iStream = null;
// Buffer to read 10K bytes in chunk
//byte[] buffer = new Byte[10000];
// Buffer to read 1024K bytes in chunk
byte[] buffer = new Byte[1048576];
// Length of the file:
int length;
// Total bytes to read:
long dataToRead;
try
{
// Open the file.
iStream = new FileStream(filepath, FileMode.Open, FileAccess.Read, FileShare.Read);
// Total bytes to read:
dataToRead = iStream.Length;
HttpContext.Current.Response.ContentType = contentType;
HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(filename, System.Text.Encoding.UTF8));
// Read the bytes.
while (dataToRead > 0)
{
// Verify that the client is connected.
if (HttpContext.Current.Response.IsClientConnected)
{
// Read the data in buffer.
length = iStream.Read(buffer, 0, 10000);
// Write the data to the current output stream.
HttpContext.Current.Response.OutputStream.Write(buffer, 0, length);
// Flush the data to the HTML output.
HttpContext.Current.Response.Flush();
buffer = new Byte[10000];
dataToRead = dataToRead - length;
}
else
{
//prevent infinite loop if user disconnects
dataToRead = -1;
}
}
}
catch (Exception ex)
{
// Trap the error, if any.
//HttpContext.Current.Response.Write("Error : " + ex.Message);
HttpContext.Current.Response.ContentType = "text/html";
HttpContext.Current.Response.Write("Error : file not found");
}
finally
{
if (iStream != null)
{
//Close the file.
iStream.Close();
}
HttpContext.Current.Response.End();
HttpContext.Current.Response.Close();
}
}
public static void ResumableFile(string filename, string fullpath, string contentType)
{
try
{
FileStream myFile = new FileStream(fullpath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
BinaryReader br = new BinaryReader(myFile);
try
{
HttpContext.Current.Response.AddHeader("Accept-Ranges", "bytes");
HttpContext.Current.Response.Buffer = false;
long fileLength = myFile.Length;
long startBytes = 0;
//int pack = 10240; //10K bytes
int pack = 1048576; //1024K bytes
if (HttpContext.Current.Request.Headers["Range"] != null)
{
HttpContext.Current.Response.StatusCode = 206;
string[] range = HttpContext.Current.Request.Headers["Range"].Split(new char[] { '=', '-' });
startBytes = Convert.ToInt64(range[1]);
}
HttpContext.Current.Response.AddHeader("Content-Length", (fileLength - startBytes).ToString());
if (startBytes != 0)
{
HttpContext.Current.Response.AddHeader("Content-Range", string.Format(" bytes {0}-{1}/{2}", startBytes, fileLength - 1, fileLength));
}
HttpContext.Current.Response.AddHeader("Connection", "Keep-Alive");
HttpContext.Current.Response.ContentType = contentType;
HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(filename, System.Text.Encoding.UTF8));
br.BaseStream.Seek(startBytes, SeekOrigin.Begin);
int maxCount = (int)Math.Floor((double)((fileLength - startBytes) / pack)) + 1;
for (int i = 0; i < maxCount; i++)
{
if (HttpContext.Current.Response.IsClientConnected)
{
HttpContext.Current.Response.BinaryWrite(br.ReadBytes(pack));
}
else
{
i = maxCount;
}
}
}
catch
{
HttpContext.Current.Response.ContentType = "text/html";
HttpContext.Current.Response.Write("Error : file not found");
}
finally
{
br.Close();
myFile.Close();
}
}
catch
{
HttpContext.Current.Response.ContentType = "text/html";
HttpContext.Current.Response.Write("Error : file not found");
}
}
}
By zeroef. Read the original answer on Stack Overflow.
I am not sure of the root cause yet but the solution is here :
http://social.msdn.microsoft.com/forums/en-US/wpf/thread/a31f9c7a-0e15-4a09-a544-bec07f0f152c
Seems to be a popular bug :)
By mishal153. Read the original answer on Stack Overflow.
If it can help, I was having the exact same problem (as stated here and here). I bring here one of the possible CAUSE of this.
I am using a ElementHost (c#, .net4.0, winform, VS2012) for a great WPF UserControl. Everything was working Great. In my UserControl behind-code, I was using a class that was caming from another DLL, used to store progression of certain task. For example (it is close to reality) :
public class SI_MyProgressionHelper
{
public string gstr_OverallProgress_Description { get; set; }
public int gint_OverallProgress_ActualValue { get; set; }
public int gint_OverallProgress_MaximumValue { get; set; }
}
I then wanted to "plug" that class into my WPF progressBar/textBox to report the progression as it goes. However (and that's another conversation), WPF needs to have INotifyPropertyChanged applied to every single property you want to plug in WPF (to automatically update controls in WPF). That's one of the ugliest thing I ever saw, but it is what it is (And I know i must missed something..)
Anyway, to complies to WPF Binding mecanism between my ProgressBar/textbox and my SI_MyProgressionHelper class, i've modified the class (which I repeat, is in another DLL) to this :
public class SI_MyProgressionHelper : INotifyPropertyChanged
{
private string _gstr_OverallProgress_Description = "";
public string gstr_OverallProgress_Description { get { return _gstr_OverallProgress_Description; } set { _gstr_OverallProgress_Description = value; RaisePropertyChanged("gstr_OverallProgress_Description"); } }
private int _gint_OverallProgress_ActualValue = 0;
public int gint_OverallProgress_ActualValue { get { return _gint_OverallProgress_ActualValue; } set { _gint_OverallProgress_ActualValue = value; RaisePropertyChanged("gint_OverallProgress_ActualValue"); } }
private int _gint_OverallProgress_MaximumValue = 9999;
public int gint_OverallProgress_MaximumValue { get { return _gint_OverallProgress_MaximumValue; } set { _gint_OverallProgress_MaximumValue = value; RaisePropertyChanged("gint_OverallProgress_MaximumValue"); } }
protected virtual void RaisePropertyChanged(string propName)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(propName));
}
public event PropertyChangedEventHandler PropertyChanged;
}
BAM! The error occurs on any random integer property of any XMLElement (Height, Width, etc...) of my UserContrl (exactly as stated here and in the other reference I stated at the top).
Applying the solution brought here does correct my problem : In my Program.cs Main() method :
[DllImport( "msvcr70.dll", CallingConvention = CallingConvention.Cdecl )]
public static extern int _fpreset();
and then, in my UserControl.xaml.cs, in the constructor :
public UserControl1()
{
Program._fpreset();
InitializeComponent();
}
Also, and that's the reason why I wrote that comment : by removing the INotifyPropertyChanged on my Helper class (and other stuff related), the problem goes away. (but my WPF is sad because my code is too short for him).
Hope this additionnal information may help someone having the same problem.
Also, for all my french colleague, here is the french error encountered :
Il y a eu un dépassement de capacité positif ou négatif dans l'opération arithmétique.
By Simon. Read the original answer on Stack Overflow.
Source: Stack Overflow