Home > Net >  I want to make a method that throws new exception which is then caught where the method is called fr
I want to make a method that throws new exception which is then caught where the method is called fr

Time:10-17

I have this method which i want to throw a new exception from

public void AddProduct(Product product1, Category category)
        {

        var addPToCat = new Program();
        var productExistInCategory = ProductDictionary.Any(x => x.Key == product1.ArticleNumber);

        if (!productExistInCategory)
        {
            ProductDictionary.Add(product1.ArticleNumber, category.Name );
        }
    }

The AddProduct() method is called from this method which i want to catch the exception:

 public void AddProductToCategory()
    {
        if (productExist)
        {
            if (categoryExist != null)
            {
                categoryExist.AddProduct(product, categoryExist);
                try
                {
                    if (productExistInCategoryInCategory)
                        categoryExist.ProductDictionary.Add(product.ArticleNumber, categoryName);
                }
                catch
                {
                    Console.WriteLine("Produkten finns redan");
                    Thread.Sleep(2000);
                    throw new ArgumentException("Produkten finns redan");
                }
            }
    }

Am i doing it right or is there something wrong?

CodePudding user response:

First you want to call the AddProduct method inside the try from AddProductToCategory method like this

 public void AddProductToCategory()
{
    try
        {
          categoryExist.AddProduct(product, categoryExist);
        }
}

And then in the AddProduct method you have to throw the exception like the exemple givng below:

public void AddProduct(Product product1, Category category)
       {
              if (productExistInCategory)
            {
               throw new ArgumentException();
            }
       }
        

And then go back to AddProductToCategory method and catch the exception like that:

NOTE: Dont change the code in try

 public void AddProductToCategory()
    {

        if (productExist)
        {
            if (categoryExist != null)
            {
                try
                {
                    categoryExist.AddProduct(product, categoryExist);
                }
                catch (ArgumentException)
                {
                    Console.WriteLine("Produkten finns redan");
                    Thread.Sleep(2000);
                    throw;
                }
            }

And there you go.

What we did was to try the AddProduct method untill we find or catch the exception we threw before, and thats it

  • Related