User Defined Exception in C#

Types of Exception

There are the following 2 types of exceptions:

  1. System Exception.
  2. Application Exception.

System Exception

An exception raised implicitly from some predefined condition is a “System Exception”. For example DivideByZeroException, FormatException, OverFlowException and NullReference Exception.

If you want to learn about system exceptions then read my article:

Try and Catch Blocks in C#

Application Exception

An exception that is raised explicitly by the programmer in the application on its own condition is an “Application Exception”.

It can also referred to as a “User Defined Exception”.

Now let's we learn how to develop our own User Defined Exception.

Use the following procedure to develop a User Defined Exception.

Step 1: Inherit a class from the Exception class.

For example <Your class> : Exception

Step 2: Override the string message from the exception class.

For example:

Public override string Message

{

    get

   {

        Return “Display the error Message when Exception Occur”

   }

} 

Step 3: In the other class, if an exception occurs that throws an exception for the creation of an object of your own exception class then do something.

For example:

Throws new <Own Exception name>

Let's start with a demonstration.

Demo

  1. Open Visual Studio 2012.
  2. Select "File" -> "New" -> "Project..." as in the following:

    New Project

  3. Select the language as “Visual C#” and the template as "Console Application" then provide an appropritate name. I gave it the name UserDefindException. Select a Location then click on "OK".

    Console Application

  4. Add a new class by right-clicking on Solution Explorer. Add a new item; choose "Class", provide the name as NegativeNumberExceptionDemo.cs then click on "OK".

    Add class

  5. Use the following code in the class.

    code in the class

  6. Add a new class “UserDefindDemo” and click on the Add button.

    Add new class

  7. Use following code in the class.

    class

Save it then debug the application; check for any error occuring, if there is no error then run the program, the following output will be shown:

debug the application

In other words when the result is negative then it throws an exception and displays the error message.

That is created by the user.

In that way we can create own User Defined Exception.


Similar Articles