User Defined Exception in C#
In this article you will learn about user defined exceptions in C#.
Types of Exception
There are the following 2 types of exceptions:
- System Exception.
- Application 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#
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.
Public override string Message
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.
Throws new <Own Exception name>
Let's start with a demonstration.
- Open Visual Studio 2012.
- Select "File" -> "New" -> "Project..." as in the following:
- 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".
- 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".
- Use the following code in the class.
- Add a new class “UserDefindDemo” and click on the Add button.
- Use following code in the 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:
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.