System.ArithmeticException

The exception that is thrown for errors in an arithmetic, casting, or conversion operation.

Minimum version: >= 1.1 >= Core 1.0

Statistics

28

How to handle it

try
{

}
catch (System.ArithmeticException e)
{

}
try
{

}
catch (System.ArithmeticException e) when (e.Message.Contains("something"))
{

}
try
{

}
catch (System.ArithmeticException e) when (LogException(e))
{

}

private static bool LogException(Exception e)
{
    logger.LogError(...);
    return false;
}

How to avoid it

You typically don't want to catch ArithmeticException since it's used as a base class for different types of arithmetic errors.

Before
int divisor = 0;

try
{
    int result = dividend / divisor;
}
catch (ArithmeticException e) // Don't use the base type
{
}
After
int divisor = 0;

try
{
    int result = dividend / divisor;
}
catch (DivideByZeroException e) // Use the specific type instead
{
}

Links

YouTube videos

Possible fixes from StackOverflow

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);
}

In the source of that BigInteger, there is:

// maximum length of the BigInteger in uint (4 bytes)
// change this to suit the required level of precision.
private const int maxLength = 70;

The length is counted in limbs, each limb is 32 bits in this implementation. Additionally, the topmost bit of the topmost limb is treated as a sign bit. Therefore, without changing the source the maximum number that can be stored in this kind of BigInteger (this limit does not apply to the BigInteger in System.Numerics) is 270*32-1-1, or in other words, there are 2239 "normal" bits available.

That allows for some fairly big integers, but not big enough: according to Wolfram Alpha fib(3227) requires just over 2239 bits, therefore it does not fit.

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)]

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");
        }
    }     
}

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 :)