I experimented a lot with re throwing exceptions and came on to following conclusions:
1)We might want to re throw if we want to give more details about exception like (Inner exception)
2)we may re throw to entirely terminate the program ..
3)if we want to re throw and do not want to terminate the program then i will have to handle the re thrown exception in a loop ...
i tried the following while doing this:
public void input()
{
char opt;
int id;
int qty;
int ind = -1;
do
{
Console.WriteLine("Add item to cart: ");
opt = Convert.ToChar(Console.ReadLine());
if (opt == 'n' || opt == 'N')
break;
else
{
cashier.showProductList();
Console.WriteLine("Enter Product ID from above list: ");
id = Convert.ToInt32(Console.ReadLine());
foreach (Products item in cashier.ProductList)
{
if (id == item.ProductID)
{
BoughtItems.Add(item);
ind = Cashier.ProductList.IndexOf(item);
}
}
Console.WriteLine("Enter The quantity required: ");
qty = Convert.ToInt32(Console.ReadLine());
try
{
if (qty < 0)
{
throw new BuisnessException("Qty can not be -ve...", new Exception("enter a valid +ve amount"));
}
else if (qty < cashier.ProductList[ind].Quantity)
{
BoughtItems[BoughtItems.Count - 1].Quantity = qty;
TotalPrice = TotalPrice + (BoughtItems[BoughtItems.Count - 1].Quantity * BoughtItems[BoughtItems.Count - 1].price);
}
else if (qty >= cashier.ProductList[ind].Quantity)
{
throw new QuantityExceedingStockException("Item not in sufficient amount", new Exception("Enter quantity less than" + Cashier.ProductList[ind].Quantity));
}
}
catch (BuisnessException ex)
{
BoughtItems.RemoveAt(BoughtItems.Count - 1);
Console.WriteLine(ex.Message);
throw;
//throw; //Re throwing terminating the i/p loop if re thrown exception not handled in loop! :/
}
catch (QuantityExceedingStockException ex)
{
BoughtItems.RemoveAt(BoughtItems.Count - 1);
Console.WriteLine(ex.Message);
throw;
}
}
} while (true);
}
public void showCartItems()
{
foreach (Products item in _boughtItems)
{
Console.WriteLine(item.ProductID + " " + item.name + " " + item.price + " " + item.Quantity);
}
}
then in main():
do
{
try
{
cashier1.Customr.input();
}
catch (BuisnessException ex)
{
//Console.WriteLine(ex.Message);
Console.WriteLine(ex.InnerException.Message);
}
catch (QuantityExceedingStockException ex)
{
Console.WriteLine(ex.InnerException.Message);
}
//catch
//{
// Console.WriteLine("Press y below to continue shopping");
//}
Console.Write("Continue Shopping ?");
opt = Convert.ToChar(Console.ReadLine());
if (opt == 'n')
break;
else
continue;
} while (true);
Console.WriteLine("Total Price is: " + cashier1.Customr.TotalPrice);
If i do not handle the re thrown exception in loop my program terminates ... So does this means that above three Conclusions tat i presented are correct regarding re throwing exceptions??