首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > .NET > C# >

新手请问:关于try/catch块测试字段的有关问题

2012-01-19 
新手请教:关于try/catch块测试字段的问题为什么一般用try/catch嵌套的方式来逐个检测字段的合法性,而不是

新手请教:关于try/catch块测试字段的问题
为什么一般用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();
                        }

[解决办法]
嵌套方式检测:

intQuantity = int.Parse(quantityTextBox.Text);
出错时就直接到catch {}了,不再执行
decPrice = decimal.Parse(priceTextBox.Text);


顺序检测:

intQuantity = int.Parse(quantityTextBox.Text);
出错时就catch {}了,然后还要执行
decPrice = decimal.Parse(priceTextBox.Text);

热点排行