In this article I am trying to explain the concept of custom (User Define) Exception in C# and I demonstrate this concept with making a small demo.
User Define Exception
If you want users to be able to programmatically distinguish between some error conditions, you can create your own user-defined exceptions. The .NET Framework provides a hierarchy of exception classes ultimately derived from the base class Exception. Each of these classes defines a specific exception, so in many cases you only have to catch the exception. You can also create your own exception classes by deriving from the Exception class.
Example: -
using System;
namespace MindstickCustomeExceptionDemo
{
public class MindstickEmployeeListNotFoundException : Exception
{
public MindstickEmployeeListNotFoundException()
{
}
public MindstickEmployeeListNotFoundException(string message):base(message)
{
}
}
class CustomException
{
static void Main(string[] args)
{
try
{
throw new MindstickEmployeeListNotFoundException("\n\n::Mindstick Employee List not found::\n\n");
}
catch (MindstickEmployeeListNotFoundException ce)
{
Console.WriteLine(ce.ToString());
}
Console.ReadKey();
}
}
}
Code Description: -
1. Using System (include the System namespace).
2. Create a namespace with MindstickCustomeExceptionDemo named.
4. Create a public class with MindstickEmployeeListNotFoundException
named and inherit the Exception class.
6. Create a class constructor of MindstickEmployeeListNotFoundException
without parameter.
9. Create a class constructor of MindstickEmployeeListNotFoundException
with parameter.
13.Create a class with CustomException named.
15. Create Main method.
17.Start try block.
19. Thrown the exception with its exception class name.
21. This catch block.
23. Print the exception message.
Output: -
If I pass any message in the form of string while thrown the exception then on console screen show passed string message.
In line number 19. I have pass throw newMindstickEmployeeListNotFoundException("\n\n::Mindstick Employee List not found::\n\n");then it message will show console screen.
ScreenShot:
In line number 19. I don't pass any message in string format such as: - throw newMindstickEmployeeListNotFoundException();then it will show system message in console screen.
Leave Comment