我對C#相當陌生。雖然拋出其他條件的例外工作正常,但字符串(或缺少條目將是更好的術語)不起作用。它直接捕獲(FormatException)消息。字符串不被拋出
我知道,我可以把相同的語句如果(txtSubtotal.Text ==「」)在上述catch語句,它會正常工作,但我真的很好奇,爲什麼我不能做到這一點拋出一個新的異常。
private void btnCalculate_Click(object sender, EventArgs e)
{
try
{
decimal subtotal = Decimal.Parse(txtSubtotal.Text);
{
if (txtSubtotal.Text == "")
throw new Exception("Subtotal is a Required Field.");
if (subtotal <= 0)
throw new Exception("Subtotal must be greater than 0");
if (subtotal >= 10000)
throw new Exception("Subtotal must be less than 10000");
}
decimal discountPercent = .25m;
decimal discountAmount = subtotal * discountPercent;
decimal invoiceTotal = subtotal - discountAmount;
discountAmount = Math.Round(discountAmount, 2);
invoiceTotal = Math.Round(invoiceTotal, 2);
txtDiscountPercent.Text = discountPercent.ToString("p1");
txtDiscountAmount.Text = discountAmount.ToString();
txtTotal.Text = invoiceTotal.ToString();
txtSubtotal.Focus();
}
catch (FormatException)
{
MessageBox.Show("Please enter a valid number for the Subtotal field.", "Entry Error");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message + "\n" + "\n", "Entry Error");
}
}
請勿使用異常來控制邏輯流程。這是一個非常不好的習慣,作爲一名新程序員,你應該儘量避免這樣做。 –