Exception Handling
Here is a small example for Exception handling using a custom made exception class.
Here is a class to handle our exception. It is used to generate an exception when there is not enough stock of an item when tried to sell it.
The class just overrides the ToString() method here for simplicity.
class NotEnoughStockException:Exception
{
public override string ToString()
{
return "Not Enough Stock";
}
}
The SalesItem class has methods to sell and show item.
class SalesItem
{
string name;
int stock;
public SalesItem(string Name,int Stock)
{
this.name = Name;
this.stock = Stock;
}
public void Sell(int Qty)
{
if (Qty > stock)
throw new NotEnoughStockException();
stock -= Qty;
}
public void Show()
{
Console.WriteLine("{0} :{1}Kg",name,stock);
}
}
And the main program just creates an object of SalesItem class with some initial values and calls the Show and Sell methods
class Program
{
static void Main(string[] args)
{
try
{
SalesItem i = new SalesItem("Dal", 10);
i.Show();
i.Sell(5);
i.Show();
i.Sell(13);
i.Show();
}
catch (NotEnoughStockException e)
{
Console.WriteLine("There was an error!");
Console.WriteLine(e);
}
}
}
}
