异常处理 C#

Exception Handling C#

我在这方面相对较新,一直在绞尽脑汁试图让我的程序正常工作,但就是不行。我正在使用 Visual Studio 2012 C# 开发表单应用程序。

当用户输入值大于 0 但小于 10,000 时,我需要它产生一个明显的错误消息。它还必须在用户输入非数字值时产生明显的错误消息,在用户根本无法输入任何值时产生明显的错误消息。

到目前为止,我编写的代码会在用户输入非数字值或根本无法输入任何值时产生明显的错误消息,但在用户输入时不会触发错误消息低于或高于要求范围的值。

就好像编译器忽略了我为第一个 exception/overflow 异常编写的代码,而只识别第二个也是最后一个异常的代码。我的代码没有编码错误。看来我的问题出在逻辑上。

如果可以,请帮助我。我的代码在下面谢谢!

    private void btnCalculate_Click(object sender, System.EventArgs e)
    {

        try
        {
            {

                decimal subtotal = Convert.ToDecimal(txtSubtotal.Text);
                decimal discountPercent = .25m;
                decimal discountAmount = subtotal * discountPercent;
                decimal invoiceTotal = subtotal - discountAmount;

                lblDiscountPercent.Text = discountPercent.ToString("p1");
                lblDiscountAmount.Text = discountAmount.ToString("c");
                lblTotal.Text = invoiceTotal.ToString("c");

            }
        }
        catch (OverflowException)

        {
            decimal subtotal = Convert.ToDecimal(txtSubtotal.Text);

            if (subtotal <= 0)
            {
                MessageBox.Show("Subtotal must be greater than [=10=].00. ", "Error Entry");
                txtSubtotal.Focus();
            }

             if (subtotal >= 10000)

            {
                MessageBox.Show("Subtotal must be less than 000.00. ", "Error Entry");
                txtSubtotal.Focus();
            }
        }

        catch (Exception)
        {

            if (txtSubtotal.Text == "")
            {
                MessageBox.Show("Subtotal is a required field. ", "Error Entry");
            }


            else
            {
                MessageBox.Show(
                 "Please enter a valid Number for the subtotal field.", "Error Entry");
                txtSubtotal.Focus();
            }


            }           

        }




    private void btnExit_Click(object sender, System.EventArgs e)
    {
        this.Close();
    }

    private void txtSubtotal_TextChanged(object sender, EventArgs e)
    {

    }

}

}

正如我在评论中提到的,您应该考虑将代码移出 catch 块。

在这种情况下,您应该考虑创建一个简单的方法来验证您的输入并生成输出消息。

给你举个例子:

  private bool IsPageValid()  
  {
           string errorMessage = string.Empty;               
           bool isValid = true;
           if (subtotal <= 0)
           {
           errorMessage+="<li>"+"<b>Subtotal must be greater than [=10=].00. ", "Error Entry"+ "</b><br/>";
           txtSubtotal.Focus();
           isValid=false;
           }
   }

Likewise write other clause of validations in this function..This will validate each of your condition and if fails it would make the isValid false thus not allowing users to submit.

现在您应该在单击按钮时调用此函数。

 protected void btnSubmit_Click(object sender, EventArgs e)
    {

            ClearMessage();
            if (IsPageValid().Equals(true))
            {
             // allow next action to happen.
            }
     }

代码应如下所示

try {
    decimal subtotal = Convert.ToDecimal(txtSubtotal.Text);
    try {
        if(x<0 || x>10000){
            throw new OverFlowException("");
        }
        //Do what ever you want
    }
    catch(Exception ex){
        // catch overflow
    }
}
catch(Exception ex){
    // catch nonnumeric value
}

我会为此使用 KeyEvent press enter 或 Leave 事件,如果用户输入不是字符串,首先我需要创建通用 class 进行验证。 健康)状况: 1 验证输入是否不是字符串 Im 使用 generic for general purpose class.

   public class iCnF()
   {
    public static System.Boolean IsNumeric(System.Object Expression) 
      {
        if (Expression == null || Expression is DateTime)
            return false;
        if (Expression is Int16 || Expression is Int32 || Expression is Int64 || Expression is Decimal || Expression is Single || Expression is Double || Expression is Boolean)
            return true;
        try 
        {
            if(Expression is string)
                Double.Parse(Expression as string);
            else
                Double.Parse(Expression.ToString());
                return true;
        } catch {} // just dismiss errors but return false
            return false;
     }
}
  1. 然后我需要验证输入是否不为空

       private void txtSubtotal_KeyDown(object sender, KeyEventArgs e)
       {
        if (e.KeyCode == Keys.Enter || e.KeyCode == Keys.Tab)
        {
            if (txtSubtotal.Text.Length > 0)
            {
                bool sd = iCnF.IsNumeric(txtSubtotal.Text);
                if (sd == false)
                {
                   MessageBox.Show("Subtotal must be a numeric value. ", "Error Entry");
    
                   txtSubtotal.Clear();
                   txtSubtotal.Focus();
                }
                else
                {
                    decimal subtotal = Convert.ToDecimal(txtSubtotal.Text);
                    if (subtotal <= 0)
                    {
                        MessageBox.Show("Subtotal must be greater than [=11=].00. ", "Error Entry");
                        txtSubtotal.Focus();
                   }
    
                   if (subtotal >= 10000)
                   {
                       MessageBox.Show("Subtotal must be less than 000.00. ", "Error Entry");
                       txtSubtotal.Focus();
                   }
               }
           }
           else
           {
               MessageBox.Show("Subtotal must not be empty. ", "Error Entry");
               txtSubtotal.Focus();
           }
       }
      }  
    
  2. 如果不是空的和数值我的小计 <= 0 和小计 >= 10000

希望这对你有帮助:D