私はC#をかなり新しくしています。他の条件の例外をスローすることはうまくいきますが、文字列(またはエントリの欠落は使用する方が良いでしょう)が機能しません。代わりにcatch(FormatException)メッセージにまっすぐに進みます。文字列がスローされない
上記のcatchステートメントで(txtSubtotal.Text == "")if()と同じステートメントを入れることができることは知っていますが、うまくいくでしょうが、なぜ私がこれを行うことができないのか不思議です新しい例外がスローされます。メソッドへのパラメータ(txtSubtotal.Text
)は変換できない場合
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");
}
}
論理フローを制御するために例外を使用しないでください。これは非常に悪い習慣であり、新しいプログラマとして、あなたはそれを避けようとするべきです。 –