2016-07-05 61 views
0

我對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"); 
    } 
} 
+1

請勿使用異常來控制邏輯流程。這是一個非常不好的習慣,作爲一名新程序員,你應該儘量避免這樣做。 –

回答

2

方法Decimal.Parse()意願拋出FormatExceptions如果參數(txtSubtotal.Text)該方法是不可轉換。爲了避免這種情況,你可以你信任Decimal.TryParse()做同樣的,沒有任何try..catch試試下面的代碼:

decimal subtotal; 
if (Decimal.TryParse(txtSubtotal.Text, out subtotal)) 
{ 
    if (subtotal <= 0) 
     MessageBox.Show("Subtotal must be greater than 0"); 
    else if (subtotal >= 10000) 
     MessageBox.Show("Subtotal must be less than 10000"); 
    else 
    { 
    // Process your code here 
    } 
} 
else 
{ 
    MessageBox.Show("Invalid Input! Subtotal Expecting a Decimal value"); 
} 
+1

你在TryParse調用中缺少一個'out小計' – Blorgbeard

+0

@Blorgbeard:謝謝,我已經更新了答案 –

0

夫婦的東西在這裏,首先我認爲這是一個邏輯混亂的問題,您預期的結果。藉此摘錄...

decimal subtotal = Decimal.Parse(txtSubtotal.Text); 
{ 
    if (txtSubtotal.Text == "") 
    throw new Exception("Subtotal is a Required Field."); 
... 

Decimal.Parse總是要扔在一個空字符串,或任何其他值如不能轉換爲十進制出現FormatException。這意味着下一個條件永遠不會被執行。如果它被執行了,它永遠不會是真的,因爲你只是用一個成功的Decimal.Parse證明了它。

0

此行爲是由於您的字符串爲空或空,並且代碼嘗試將空值或空字符串解析爲小數。

在嘗試解析字符串之前檢查字符串會更好。你也可以使用字符串類中的string.IsNullOrWhitespace方法輕鬆地檢查字符串的內容。

像這樣:

try 
{ 
    if (string.IsNullOrWhitespace(txtSubtotal.Text)) 
     throw new Exception("Subtotal is a Required Field."); 

    decimal subtotal = Decimal.Parse(txtSubtotal.Text); 

    //rest of your code. 

通過這樣的代碼和字符串爲空或空白,基本將引發異常......但如果字符串是不是NULL或空格,它也不是有效的數字格式,那麼代碼將拋出FormatException。

相關問題