为什么一般用try/catch嵌套的方式来逐个检测字段的合法性,而不是顺序的去检测,这两种方式有区别吗?嵌套方式检测:
            try
            {
                intQuantity = int.Parse(quantityTextBox.Text);
                try
                {
                    decPrice = decimal.Parse(priceTextBox.Text);
                }
                catch 
                {
                    MessageBox.Show("Price must be numeric");
                    priceTextBox.SelectAll();
                    priceTextBox.Focus();
                }            }
            catch 
            {
                MessageBox.Show("Quantity must be numeric");
                quantityTextBox.SelectAll();
                quantityTextBox.Focus();
            }
顺序检测:
            try
            {
                intQuantity = int.Parse(quantityTextBox.Text);
               
            }
            catch
            {
                MessageBox.Show("Quantity must be numeric");
                quantityTextBox.SelectAll();
                quantityTextBox.Focus();
            }
            try
            {
                
                decPrice = decimal.Parse(priceTextBox.Text);
            }
            catch
            {
                MessageBox.Show("Price must be numeric");
                priceTextBox.SelectAll();
                priceTextBox.Focus();
            }

解决方案 »

  1.   

    嵌套方式检测:intQuantity = int.Parse(quantityTextBox.Text);
    出错时就直接到catch {}了,不再执行
    decPrice = decimal.Parse(priceTextBox.Text);
    顺序检测:intQuantity = int.Parse(quantityTextBox.Text);
    出错时就catch {}了,然后还要执行
    decPrice = decimal.Parse(priceTextBox.Text);
      

  2.   

    是不是想将字符串转化为 数字型的阿,如果是,可以考虑使用正则阿,一个patterns 就ok了。而且对于大型数据来说,正则比try...catch...finally...要好得多。private const string NUMBER_PATTERNS = "^\\-?\\d+\\.?(\\d+)?$";
    private bool IsNumumber(string str)
            {
                return System.Text.RegularExpressions.Regex.IsMatch(str, NUMBER_PATTERNS, System.Text.RegularExpressions.RegexOptions.Compiled | System.Text.RegularExpressions.RegexOptions.IgnoreCase);
            }
    调用:
    this.lblResult.Text = this.IsNumumber(this.txtSrc.Text).ToString();
      

  3.   

    谢谢楼上的兄弟,只是我才看到try/catch这儿 呵呵 以后还得多多请教