简体   繁体   中英

C# System.OverflowException Error in loops

I'm trying to simplify someone's coding to let the codes be more readable. When I run the following code, however, I encountered "System.OverFlowException" error. I run the code in visual studio IDE. The function, "Transmit_Data" is used only to store an array of data. "TotalIndexToMod" is the array's length, "CurrentLoopIndexCnt" is the current looping index number of "TotalIndexToMod". Below are the codes (in C#) :

int TotalIndexToMod = 28;
int MaxLoopIndexCnt = 16;


for (int mod = 0; mod < TotalIndexToMod; mod++)
{

    int LeftToMod = MaxLoopIndexCnt - CurrentLoopIndexCnt;

    Transmit_Data(mod, LeftToMod);

    CurrentLoopIndexCnt++;

    Console.WriteLine("CurrentIndexToMod / Mod/ Index : " + Convert.ToInt16(mod));
    CurrentIndexToMod = mod;
    Console.WriteLine("CurrentLoopIndexCnt : " + Convert.ToInt16(CurrentLoopIndexCnt));
    Console.WriteLine("MaxLoop : " + Convert.ToInt16(MaxLoop));
    Console.WriteLine("MaxLoopIndexCnt : " + Convert.ToInt16(MaxLoopIndexCnt));


    if (CurrentLoopIndexCnt > MaxLoopIndexCnt)
    {
        CurrentLoopCnt++;

        if (CurrentLoopCnt > MaxLoop) // last loop end
        {
            // byte Mod_State = (byte)(RxMsg.DATA[0] & 0x03);

            if (CurrentIndexToMod == 128)
            {
                //do something
            }
            else
            {
                //do something
            }
        }
        else
        {
            if (CurrentLoopCnt < MaxLoop)
            {
                MaxLoopIndexCnt = 16;
            }
            else if (CurrentLoopCnt == MaxLoop) // last loop
            {
                MaxLoopIndexCnt = SpareMaxLoopIndexCnt;
            }

            CurrentLoopIndexCnt = 1;
        }

    }

}

Most probably error occurs in method Convert.ToInt16 . So please make sure that values are not outside the range of the Int16 type.

Please also consider overloaded method WriteLine with format string parameter. In this way the following line of code:

Console.WriteLine("CurrentIndexToMod / Mod/ Index : " + Convert.ToInt16(mod));

will be look like so:

Console.WriteLine("CurrentIndexToMod / Mod/ Index : {0}", mod);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM