C# Tutorials and offshore development in India
    Tutorials   Resources   Forum   Reviews   Communities   Interview   Jobs   Projects   Training   Your Ad Here    
Silverlight Games | Mentor | Code Converter | Articles | Code Factory | Computer Jokes | Members | Peer Appraisal | IT Companies | Bookmarks | Polls | Revenue Sharing | Lobby | Gift Shop |


Prizes & Awards
My Profile



Active Members
TodayLast 7 Days more...






Resources » Code Snippets » C# Syntax »

Exception Handling


Posted Date: 18 Dec 2008    Resource Type: Code Snippets    Category: C# Syntax
Author: JayeshMember Level: Gold    
Rating: 1 out of 5Points: 15



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);
}
}
}
}







Responses


No responses found. Be the first to respond and make money from revenue sharing program.

Feedbacks      
Popular Tags   What are tags ?   Search Tags  
Sign In to add tags.
Exception in c#  .  Exception handling  .  Error handling  .  

Post Feedback


This is a strictly moderated forum. Only approved messages will appear in the site. Please use 'Spell Check' in Google toolbar before you submit.
You must Sign In to post a response.
Next Resource: Simple code to make data table
Previous Resource: Use a session variable in the class files in c# ASP.Net
Return to Discussion Resource Index
Post New Resource
Category: C# Syntax


Post resources and earn money!
 
More Resources



dotNet Slackers

About Us    Contact Us    Privacy Policy    Terms Of Use