我正试图让try-catch工作。我已经建立了一个网站,其中一部分是提取现金。当我将字符放在撤销文本框中时,显示文本为:“交易完成 - 拿走你的钱。”
这是我的代码。我是初学程序员,我不知道该怎么做。已在全局中声明未在此代码中显式声明的变量。
protected void continue_btn_Click(object sender, EventArgs e)
{
// if the input of amount is not empty assign amount to a conversion integer of txtAmount.Text
if (txtAmount.Text != "")
{
try
{
amount = Convert.ToInt32(txtAmount.Text);
hBos.setWithdrawls(amount);
}
catch (Exception ex)
{
resultLbl.Text = ex.Message;
}
}
//if a radio button has been selected convert the selected amount and assign it to the amount variable
else
{
amount = Convert.ToInt32(amountRadioBtnList.SelectedValue);
}
//if amount is not a multiple of 10 display an error message
if (amount % 10 != 0)
{
resultLbl.Text = "Error- amount must be a multiple of 10";
return;
}
else
{
//if euro is selected convert to euro with exchange rate
if (currencyRadioBtnList.SelectedValue == "Euro")
{
decimalAmount = amount / hBos.getExchangeRate();
}
//decimal amount is equal to amount
else
{
decimalAmount = amount;
}
}
//if decimalAmount is greater than 250
//Displays error message
if (decimalAmount > 250)
{
resultLbl.Text = "Error - cannot withdraw more than £250";
return;
}
//invoke withdraw method using login. pin and decimal amount as parameters
success = hBos.withdraw(login, pin, decimalAmount);
//if the withdraw fails
//Displays error message
if (success == false)
{
resultLbl.Text ="Error - Insufficient funds";
}
//display message that transaction is sucessful
else
{
resultLbl.Text = "Transaction Completed - take your money";
}
//if the print receipt check box has been checked
// save withdrawl to decimal amount
//Then go to withdrawl reciept webpage
if(checkPrintedRecipt.Checked == true)
{
Session["withdrawl"] = decimalAmount;
Response.Redirect("WithdrawlReceipt");
}
}
答案 0 :(得分:1)
如果您想查看异常消息,请在设置后添加return
:
// if the input of amount is not empty assign amount to a conversion integer of txtAmount.Text
if (txtAmount.Text != "")
{
try
{
amount = Convert.ToInt32(txtAmount.Text);
hBos.setWithdrawls(amount);
}
catch (Exception ex)
{
resultLbl.Text = ex.Message;
return;
}
}
就像你已经有一些其他失败条件一样。目前,您的catch
设置了一条消息,但该方法仍在继续。然后它试图撤销0
并成功。
此代码还存在一些其他问题 - amount
和decimalAmount
显然是字段而不是局部变量。这个事实隐藏了这样一个事实:在这个逻辑中似乎存在控制流路径未能将decimalAmount
设置为任何合理的,因此代码将使用之前使用中遗留的任何值。更喜欢将变量声明为尽可能接近它们的位置(使用局部变量而不是字段,在需要它们的最小块内声明它们)以发现这些类型的错误。
此外,您可能需要考虑使用Convert.ToInt32
而不是try
/ catch
块中的int.TryParse
。这是一种期望解析可能失败的方法,并允许您优雅地处理它,而不是throw
和catch
异常。
答案 1 :(得分:0)
无论您在其余代码中执行了什么操作,都会忽略您的第一个if语句,因此永远不会观察到try-catch块。 原因是您在文本框中放了一些字符,尽管if块检查空输入!
当我将字符放在撤销文本框中时,diplay文本是: 交易完成 - 拿走你的钱。
我认为你试图编写类似这样的代码:
if (txtAmount != null)
{
// try-catch block
}
此语句可能是合理的,因为它表明您希望防止可能的nullreferenceexception。你在这里使用的结构是一种矛盾