简体   繁体   English

如何处理System.OverflowException

[英]How to handle System.OverflowException

I have one simple windows application in that amount Textbox is there. 我有一个简单的Windows应用程序,文本框就在那里。 When i enter amount into amount textbox it will convert it to words in another textbox named txtrupees . 当我在金额文本框中输入金额时,它会将其转换为另一个名为txtrupees文本框中的txtrupees Amount Textbox field maximum length is set to 11 places in that last 3 places .00. 金额文本框字段最大长度设置为最后3个位置.00的11个位置。

My problem is now when i Enter amount with .00 it is working fine. 我现在的问题是,当我输入金额为.00时工作正常。 But if i enter 11 places it will giving following Error: 但如果我进入11个位置,它将给出以下错误:

System.OverflowException' occurred in mscorlib.dll Value was either too large or too small for an Int32.tried following code. mscorlib.dll中发生System.OverflowException对于Int32.tried下面的代码,值太大或太小。

How can I prevent this kind of error? 我怎样才能防止出现这种错误?

private void txtamount_TextChanged(object sender, EventArgs e)
{
    if (txtamount.Text != string.Empty)
    {
        string[] amount = txtamount.Text.Split('.');
        if (amount.Length == 2)
        {
            int rs, ps;
            int.TryParse(amount[0], out rs);
            int.TryParse(amount[1], out ps);

            string rupees = words(rs);
            string paises = words(ps);
            txtrupees.Text = rupees + " rupees and " + paises + " paisa only ";
        }
        else if (amount.Length == 1)
        {
            string rupees = words(Convert.ToInt32(amount[0]));
            txtrupees.Text = rupees + " rupees only";
        }
    }
}

The issue comes from Convert.ToInt32(amount[0]) where amount[0] can be almost anything, including being superior to Int.MaxValue or inferior to Int.MinValue which would cause an overflow. 问题来自Convert.ToInt32(amount[0]) ,其中amount[0]几乎可以是任何东西,包括优于Int.MaxValue或低于Int.MinValue ,这将导致溢出。

Use int.TryParse(amount[0], out foo); 使用int.TryParse(amount[0], out foo); and use foo : 并使用foo

else if (amount.Length == 1)
{
    int ps;
    if(int.TryParse(amount[0], out ps))
    {
        string rupees = words(ps);
        txtrupees.Text = rupees + " rupees only";
    }
    else
        txtrupees.Text = "Invalid number";
}

If you want to deal with bigger numbers, you can use Int64 , Double or Decimal 如果要处理更大的数字,可以使用Int64DoubleDecimal

a number that has 11 places is larger than a Int32 number. 有11个位数的数字大于Int32数字。 I suggest you should use int64 instead of int32 https://msdn.microsoft.com/en-us/library/29dh1w7z.aspx 我建议你应该使用int64而不是int32 https://msdn.microsoft.com/en-us/library/29dh1w7z.aspx

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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