当我同时正确输入帐号和提款金额时,我会不断收到“输入整数”消息框。
假设我为帐号输入“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");
}
}
答案 0 :(得分:3)
格式字符串指定三个参数,但您只提供了两个:
String.Format("Withdrawn {0} from {1}\nBalance now: {2}", am, aN)
抛出一个FormatException
,但不是你编写FormatException
catch块时想到的那个。
因此,为了避免这种异常,您需要一种方法来获取可以传递给String.Format
的变量中的新余额。 (您也可以使用比aN
和am
更长,更具描述性的变量名称。)
关于异常处理问题的最直接答案是对方法采取的单独操作使用单独的try块,即解析两个不同的字符串,执行事务,将消息格式化为用户,以及显示信息。这样就可以将FormatException
引发的int.Parse
处理与FormatException
引发的string.Format
的处理分开。
然而,正如Arion建议的那样,对于解析用户输入,通常最好使用TryParse
而不是捕获异常(捕获FormatException
的问题是一个很好的例子!)。当然,这假设您正在使用具有 TryParse
方法的框架版本;它们是在2.0版本中添加的。
答案 1 :(得分:1)
为什么你不能这样做:
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
}