首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何处理System.OverflowException

如何处理System.OverflowException
EN

Stack Overflow用户
提问于 2017-04-26 10:01:16
回答 2查看 1.8K关注 0票数 4

我有一个简单的窗口应用程序,其数量就是Textbox。当我在“金额”文本框中输入“金额”时,它将将其转换为另一个名为“txtrupees”的文本框中的单词。“金额”文本框字段最大长度设置为11个位置,最后3个位置为.00。

我现在的问题是,当我输入.00的数量时,它工作得很好。但是,如果我进入11个位置,它会出现以下错误:

System.OverflowException‘发生在mscorlib.dll值中,对于in 32尝试过的代码来说,它们要么太大要么太小。

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

代码语言:javascript
复制
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";
        }
    }
}
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2017-04-26 10:07:47

这个问题来自于Convert.ToInt32(amount[0])amount[0]几乎可以是任何东西,包括比Int.MaxValue优越或不如Int.MinValue,这会导致溢出。

使用int.TryParse(amount[0], out foo);foo

代码语言:javascript
复制
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

票数 6
EN

Stack Overflow用户

发布于 2017-04-26 10:10:57

一个有11个位置的数字比一个Int32数大。我建议你使用int64而不是int32 https://msdn.microsoft.com/en-us/library/29dh1w7z.aspx

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/43630961

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档