【问题标题】:Getting wrong exception handled when enter input into textboxes and press button在文本框中输入输入并按下按钮时处理错误的异常
【发布时间】:2012-03-05 16:14:56
【问题描述】:

当我正确输入帐号和提款金额时,我不断收到“输入整数”消息框。

假设我输入“12”作为帐号,“50”(或“50.0”)作为金额 - 我收到“输入整数”异常消息框。

如果我什么都不输入,我会得到正确的“输入帐号”。

如果我只输入帐号(无论帐号是否存在)但将金额留空 - 按提款按钮我什么也得不到。

如果我输入帐号和金额(错误或正确,没关系),我会收到“输入和整数”异常消息框。

我哪里做错了?

private void btnWithdraw_Click(object sender, EventArgs e)
        {
            if (!txtSearch.Text.Equals(""))
            {
                if(!txtAmount.Text.Equals(""))
                {
                    try
                    {
                        int aN = int.Parse(txtSearch.Text);
                        double am = double.Parse(txtAmount.Text);
                        client.Withdraw(aN, am);
                        MessageBox.Show(String.Format("Withdrawn {0} from {1}\nBalance now: {2}", am, aN));
                        //if(client.Fi)
                        //    MessageBox.Show(String.Format("Customer {0} couldn't be found", aN));
                        //else
                        //    MessageBox.Show(String.Format("Customer {0}\nBalance: {1}C", aN, client.CustomerBalance(aN).ToString()));

                    }
                    catch (FormatException)
                    {
                        MessageBox.Show("Enter an integer");
                    }
                    catch (NullReferenceException)
                    {
                        MessageBox.Show("Customer cannot be found");
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message);
                    }
                }
            }
            else
            {
                MessageBox.Show("Enter account number");
            }
        }

【问题讨论】:

    标签: c# winforms wcf exception-handling


    【解决方案1】:

    格式字符串指定了三个参数,但您只提供了两个:

    String.Format("Withdrawn {0} from {1}\nBalance now: {2}", am, aN)
    

    这会抛出一个FormatException,但不是您在编写FormatException catch 块时考虑的那个。

    因此,为了避免该异常,您需要一种方法来获取变量中的新余额,您可以将其传递给String.Format。 (您最好使用比aNam 更长、更具描述性的变量名。)

    对于您关于异常处理的问题,最直接的答案是对方法执行的单独操作使用单独的 try 块,即解析两个不同的字符串、执行事务、格式化给用户的消息,并显示信息。这将允许将int.Parse 抛出的FormatException 的处理与string.Format 抛出的FormatException 的处理分开。

    但是,正如 Arion 所建议的,对于解析用户输入,通常最好使用 TryParse 而不是捕获异常(捕获 FormatException 的问题就是一个很好的例子!)。当然,这假设您使用的框架版本具有 TryParse 方法;它们是在 2.0 版中添加的。

    【讨论】:

    • 谢谢。问题解决了。以后我会认真注意变量命名的。
    【解决方案2】:

    你为什么不能这样做:

    int aN;
    double am;
    if(int.TryParse(txtSearch.Text,out aN) && double.TryParse(txtAmount.Text,out am))
    {
        client.Withdraw(aN, am);
        MessageBox.Show(String.Format("Withdrawn {0} from {1}\nBalance now: {2}", am, aN));
    }
    else
    {
        //Do something
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多