[英]Which Built-in C# Exception is used for check deleted item in the list
我是编程新手,我构建了一个简单的基于控制台的购物清单项目,可以添加、删除和删除项目,效果很好,但我遇到了一些问题。 如果我试图从列表中删除实际上并未添加到列表中的“移动设备”,但我的应用程序显示移动设备已成功删除的消息,是否有任何内置异常可以防止此异常,或者我必须自己编写例外? 这是我的代码
public void MyMethod()
{
var itemList = new List<string>();
int choices;
while (true)
{
Console.WriteLine("Shopping list:\n1. Add to list\n2. Remove from list\n3. List the items on the shopping list\n4. Exit");
choices = Convert.ToInt32(Console.ReadLine());
if (choices == 1)
{
Console.WriteLine("\nWhat would you like to add in the list?");
string itemAdded = Console.ReadLine();
try
{
if (itemAdded == "null" || itemAdded == "")
{
Console.WriteLine("you add nothing!!!");
}
else
{
itemList.Add(itemAdded);
Console.WriteLine(itemAdded + " is added to the list");
}
}
catch (Exception)
{
throw ;
}
}
else if (choices == 2)
{
Console.WriteLine("\nWhat would you like to remove from the list?");
string itemToRemove = Console.ReadLine();
try
{
if (itemToRemove == "null" || itemToRemove == "")
{
Console.WriteLine("you removed nothing");
}
else
{
itemList.Remove(itemToRemove);
Console.WriteLine(itemToRemove + " is successfully removed from your list");
}
}
catch (Exception)
{
throw;
}
}
else if (choices == 3)
{
foreach (string item in itemList)
{
Console.WriteLine(item);
}
}
else if (choices == 4)
{
break;
}
else
{
Console.WriteLine("please enter valid choice!!!");
}
}
}
简短的回答 - 不会抛出异常,因为异常不适用于此。 Remove 方法返回 boolean 值。 如果一个项目已被删除,那么 Remove 将返回 true。 否则为假。
稍长一点的答案:不要对这类工作使用异常。 它们不是出于这个原因而创建的。 “非预期”情况除外。 例如 - 当您没有权限时写入文件。
或者您可能希望用户输入一个数字,但他输入了一个单词。 这些是特殊情况的例子。 所以只在这种情况下使用异常。 如果您可以使用if
或通过任何其他方式检查操作是否可以完成/成功,请使用其他方式。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.