Creating custom application exception C#
Hi,
There are times when we are creating a custom class and the class needs to have it’s own application specific exception which can be thrown so that calling program can be aware of the error condition.
Say we have a class named BillingUpdate which has a condition that the billing amount should never be less than 10,000.
Say it has a function which accepts billing amount in one of it’s methods as a parameter and we need to make the user of this function aware of the condition that it can’t take billing amount less than 10000.
In this case what we can do is
create a custom class BillingException which inherits SystemException class
// creating a custom class that inherits from SystemException.
class BillingException :SystemException
{
// overloading the constructor for passing the message associated with the exception
public BillingException(string message)
: base(message)
{
}
}
Now to use this exception class we can do the following
public void GetBillingAmount(decimal billingAmount)
{
if(billingAmount < 10000M)
{
throw new BillingException(“Billing amount can’t be less than 10000”);
}
}
And the calling code can do something like this
BillingUpdate billingUpdate = new BillingUpdate();
try
{
billingUpdate.GetBillingAmount(9000M);
}
catch(BillingException ex)
{
MessageBox.Show(ex.Message);
}
Bye
This was originally posted here.

Like
Report
*This post is locked for comments