如何在try/catch中处理NoNullAllowedException

本文关键字:处理 NoNullAllowedException catch try | 更新日期: 2023-09-27 18:29:48

我在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;
                }

如何在try/catch中处理NoNullAllowedException

首先,NoNullAllowedException不适用于列表,也不适用于空值。是当您想在不允许空值的列中插入空值时抛出的异常(有关详细信息,请参阅MSDN)。

对于您的代码,在代码底部放置一个默认的返回值(但据我所见,您的代码根本不应该中断)