web
You’re offline. This is a read only version of the page.
close
Skip to main content

Notifications

Announcements

No record found.

Community site session details

Community site session details

Session Id :
Dynamics 365 Community / Blogs / Nishant Rana’s Weblog / Creating custom application...

Creating custom application exception C#

Nishant Rana Profile Picture Nishant Rana 11,325 Microsoft Employee

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.

Comments

*This post is locked for comments