繁体   English   中英

如何处理System.OverflowException

[英]How to handle System.OverflowException

我有一个简单的Windows应用程序,文本框就在那里。 当我在金额文本框中输入金额时,它会将其转换为另一个名为txtrupees文本框中的txtrupees 金额文本框字段最大长度设置为最后3个位置.00的11个位置。

我现在的问题是,当我输入金额为.00时工作正常。 但如果我进入11个位置,它将给出以下错误:

mscorlib.dll中发生System.OverflowException对于Int32.tried下面的代码,值太大或太小。

我怎样才能防止出现这种错误?

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

问题来自Convert.ToInt32(amount[0]) ,其中amount[0]几乎可以是任何东西,包括优于Int.MaxValue或低于Int.MinValue ,这将导致溢出。

使用int.TryParse(amount[0], out 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";
}

如果要处理更大的数字,可以使用Int64DoubleDecimal

有11个位数的数字大于Int32数字。 我建议你应该使用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