我有這個方法,我想從中拋出一個新例外
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 );
}
}
該AddProduct()方法是從此方法呼叫的,我想捕獲例外:
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");
}
}
}
我做得對還是有什么問題?
uj5u.com熱心網友回復:
首先,您要像這樣呼叫from方法AddProduct中的方法tryAddProductToCategory
public void AddProductToCategory()
{
try
{
categoryExist.AddProduct(product, categoryExist);
}
}
然后在該AddProduct方法中,您必須像下面給出的示例一樣拋出例外:
public void AddProduct(Product product1, Category category)
{
if (productExistInCategory)
{
throw new ArgumentException();
}
}
然后回到AddProductToCategory方法并像這樣捕獲例外:
注意:不要更改代碼
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;
}
}
你去吧。
我們所做的是對try方法,AddProduct直到我們找到或catch我們之前拋出的例外,僅此而已
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/517457.html
下一篇:java:找不到物體方法的符號
