如何在try / catch中处理NoNullAllowedException?

时间:2016-01-11 20:23:20

标签: c# try-catch handler

我在C#中有一个表单用于将一些数据输入到List中。 表单由文本框和向上和向下数字框组成。一切正常但我想在我的代码中有一个错误处理程序(try / catch),所以它会检查是否有任何文本框是空的或数字框是否为0,如果是这样的话它应该弹出一个错误信息。  我试过了:

try 
{
  //code
}
catch (NoNullAllowedException e) //tried it without the e as well
{
  //code
}

我在括号中的代码如下。有时候GetItemDetails()给我一个错误,说不是所有的代码路径都返回一个值。

任何想法为什么要这样做或如何解决?

   public iRepairable GetItemDetails()
    {

            Shirt shirt = null;
            TShirt tshirt = null;
            Trouser trouser = null;
            Shoe shoe = null;

            Boolean isShirt = true;
            Boolean isTshirt = true;
            Boolean isTrouser = true;
            Boolean isShoe = true;

        if (rdoShirt.Checked == true)
                {
                    shirt = new Shirt(txtBrand.Text, Convert.ToDouble(txtPrice.Text), Convert.ToInt32(txtAmount.Text), txtCollection.Text);

                    isTshirt = false;
                    isTrouser = false;
                    isShoe = false;
                }
                else if (rdoTShirt.Checked == true)
                {
                    tshirt = new TShirt(txtBrand.Text, Convert.ToDouble(txtPrice.Text), Convert.ToInt32(txtAmount.Text), txtCollection.Text);

                    isShirt = false;
                    isTrouser = false;
                    isShoe = false;
                }
                else if (rdoTrouser.Checked == true)
                {
                    trouser = new Trouser(txtBrand.Text, Convert.ToDouble(txtPrice.Text), Convert.ToInt32(txtAmount.Text), txtCollection.Text);

                    isShirt = false;
                    isTshirt = false;
                    isShoe = false;
                }
                else
                {
                    shoe = new Shoe(txtBrand.Text, Convert.ToDouble(txtPrice.Text), Convert.ToInt32(txtAmount.Text), txtCollection.Text);

                    isShirt = false;
                    isTrouser = false;
                    isTshirt = false;
                }



                if (isShirt)
                {
                    return shirt;
                }
                else if (isTshirt)
                {
                    return tshirt;
                }
                else if (isTrouser)
                {
                    return trouser;
                }
                else //if(isShoe)
                {
                    return shoe;
                }

1 个答案:

答案 0 :(得分:0)

首先,NoNullAllowedException不是列表,也不是空值。当您想要在不允许它们的列中插入空值时抛出的异常(更多信息,MSDN)。

对于你的代码,在代码的底部放置一个默认的返回值(但据我所知,你的代码根本不应该破解)