Introduction .NET framework provide rich support for handling many general exceptions (e.g DivideByZeroException, NotFiniteNumberException etc. This list is very big please refer to the article Exceptions in the .net framework by Srinivasan http://www.dotnetspider.com/technology/KBPages/920.aspx)
When you develop your application, need arise to have you own errors which occurs frequently and are specific to your application (e.g Cutomer not in database, Not enough balance in bank account etc). Above all these exceptions must be handled nicely by standard .NET framework (i.e using try/catch/finally block). The solution to this problem is “Create your own exception classes, and throw the exception object when error occurs”.
Details Following are the thing which you should do when you want to have your on exception handling classes: 1. Create a new exception handling class and derive it from System.Exception. 2. Override the constructor of the base class. 3. Give the class descriptive name so that the exception become little self explanatory
Example: Let’s assume I am creating a banking application using which user can either withdraw/transfer the money from the account. When ever user tries to withdraw money from account and if the balance is not sufficient then I want to throw and exception. The name of exception is “NoEnoughFundsInAccountException”
Let’s now implement the class: (Note: following is the minimum code required to build your own custom Exception class)
public class NotEnoughFundInAccountException : System.Exception { private string m_AdditionalMessgae = string.Empty; public NotEnoughFundInAccountException():base("Enough Funds are not available in the account.") {} public NotEnoughFundInAccountException(string sMessage): base("Enough Funds are not available in the account." + sMessage) { m_AdditionalMessgae = sMessage; } public NotEnoughFundInAccountException(string sMessage, Exception innerexception): base ("Enough Funds are not available in the account." + sMessage, innerexception) { m_AdditionalMessgae = sMessage; } }
Now lets see how we can make use if it in our application, consider a simple method which is executed when user requests to withdraw the money
public void WithdrawMoney(double dAmount) { if ( m_dCurrentBalance < dAmount ) throw new NotEnoughFundInAccountException(); else m_dCurrentBalance = m_dCurrentBalance - dAmount; }
Summary We can extend the .NET exception handling framework to suit our requirements and create and throw custom exceptions which are specific to application and make more sense to the user as well.
|
| Author: malaikani rajamani 30 Jan 2009 | Member Level: Bronze Points : 1 |
Nice and simple. I am very much clear about custom exception now. can you provide code block for capturing those custome exception.
|