Home > DeveloperSection > Blogs > Create custom (User Define) Exception in C#

Create custom (User Define) Exception in C#


C# C# 
Ratings:
0 Comment(s)
 7533  View(s)
Rate this:

Create custom (User Define) Exception in C#

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: -

1.  using System;

2.  namespace MindstickCustomeExceptionDemo

3.  {

4.  public class MindstickEmployeeListNotFoundException : Exception

5.  {

6.  public MindstickEmployeeListNotFoundException()

7.  {

8.  }

9.  public MindstickEmployeeListNotFoundException(string message):base(message)

10. {

11. }

12. }

13. class CustomException

14. {

15. static void Main(string[] args)

16. {

17. try

18. {

19. throw new MindstickEmployeeListNotFoundException("\n\n::Mindstick Employee List not found::\n\n");

20. }

21. catch (MindstickEmployeeListNotFoundException ce)

22. {

23. Console.WriteLine(ce.ToString());

24. }

25. Console.ReadKey();

26. }

27. }

28. }

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 new MindstickEmployeeListNotFoundException("\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 new MindstickEmployeeListNotFoundException(); then it will show system message in console screen.

Screenshot: -


Don't want to miss updates? Please click the below button!

Follow MindStick